尝试在rails 3中编写一个基本的“类似博客”应用程序, 。我需要创建方法保存post_id以及user_id在评论表(我需要为了回顾用户编写的所有评论,以显示它)Rails关联(belongs_to,has_many)无法在创建方法(用户,帖子,评论)中保存2个表格
该应用程序有用户(身份验证 - 设计) ,帖子(由用户发布 - 但我不知道它对我来说很重要)和评论(在帖子上,由用户发布)。
的评语表有POST_ID,身体,也为user_id
协会:
has_many :comments (In the Post model)
belongs_to :post (In the Comment model)
belongs_to :user (In the Comment model)
has_many :comments (In the User model)
路线:
上的文章显示显示resources :posts do
resources :comments
end
resources :users do
resources :comments
end
的评论发表形式查看:(posts/show.html.erb)
<% form_for [@post, Comment.new] do |f| %>
<%= f.label :body %>
<%= f.text_area :body %>
<%= f.submit %>
<% end %>
最后,create方法在评论控制器:
A.)如果我写这个POST_ID写入数据库
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create!(params[:comment])
redirect_to @post
end
B.)如果我写这篇文章为user_id被写入。 ..
def create
@user = current_user
@comment = @user.comments.create!(params[:comment])
redirect_to @post
end
我想:
@comment = @post.comments.create!(params[:comment].merge(:user => current_user))
但事实并非如此工作..我怎么写一个方法来保存user_id和post_id?我是否也在评论帖子表单中做了一些更改(如<%form_for [@post,@user,Comment.new] do | f |%>?)
谢谢!
非常感谢,它帮助我很多! – benoitr 2010-09-17 08:42:27