Ruby on Rails Association Form

a 夏天 提交于 2019-12-19 10:10:47

问题


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.

<%= form_for @comment do |f| %>
 <p>
 <%= f.hidden_field :user_id, :value => current_user.id %>
 <%= f.label :comment %><br />
 <%= f.text_area :comment %>
 </p>

 <p>
 <%= f.submit "Add Comment" %>
 </p>
<% end %>

回答1:


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)



来源:https://stackoverflow.com/questions/14702459/ruby-on-rails-association-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!