こんにちわ。
RailsでCouldn't find Group with 'id'= のエラーでハマってしまったので、質問します。
現在、GroupモデルとPostモデル、Userモデルを作っておいて、以下のような関連付けをしています。
//group.rb has_many: posts belongs_to: user
//post.rb belongs_to: group belongs_to: user
そして、posts_controllerは、以下のようになっています。
//posts_controller.rb def new @post = Post.new end def create @group = Group.find(params[:group_id]) //ここの行がエラーになる @post = @group.posts.new(post_params) @post.user_id = current_user.id respond_to do |format| if @post.save format.html { redirect_to @post, notice: 'Post was successfully created.' } format.json { render :show, status: :created, location: @post } else format.html { render :new } format.json { render json: @post.errors, status: :unprocessable_entity } end end end private def post_params params.require(:post).permit(:title) end
そして、posts/_formは以下の様になっています。
<%= form_for(@post) do |f| %> <div class="field"> <%= f.label :title %> <%= f.text_field :title %> </div> <div class="actions"> <%= f.submit %> </div> <% end %>
また、posts/newのページにアクセスするために、以下のリンクを張っています。
<%= link_to 'New Post', new_group_post_path(@group) %>
エラーを読むと、「Groupモデルのidが見つからないよ」との事ですが、解決策が考えつかないので、ご教授お願い致します。
追記:
書き忘れていましたが、routes.rbは以下の様になっています。
resources :groups do resources :posts end devise_for :users
routes.rbはどのように指定していますか?
routes.rbを追記しました。よろしくお願い致します。
回答1件
あなたの回答
tips
プレビュー