Ruby on Rails Association Form

前端 未结 1 1909
名媛妹妹
名媛妹妹 2021-01-14 21:33

So i\'m making a web app using ROR and I can\'t figure out what the right syntax for this form is. I\'m currently making an association type of code for comments and posts.<

相关标签:
1条回答
  • 2021-01-14 21:53

    Your form is fine, except the first line (and you don't need a hidden field for the user_id, thats done through your relationship):

    <%= form_for(@comment) do |f| %>
    

    Should be:

    <%= form_for([@post, @comment]) do |f| %>
    

    Now you render a form for creating or updating a comment for a particular post.

    However, you should change your model and controller.

    class Post
      has_many :comments
    end
    
    class Comment
      belongs_to :post
    end
    

    This will give you access to @post.comments, showing all comments belonging to a particular post.

    In your controller you can access comments for a specific post:

    class CommentsController < ApplicationController
      def index
        @post = Post.find(params[:post_id])
        @comment = @post.comments.all
      end
    end
    

    This way you can access the index of comments for a particular post.

    Update

    One more thing, your routes should also look like this:

    AppName::Application.routes.draw do
       resources :posts do
         resources :comments
       end
    end
    

    This will give you access to post_comments_path (and many more routes)

    0 讨论(0)
提交回复
热议问题