试图在 rails 3 中编写一个基本的“类似博客”的应用程序,我被关联所困。我需要创建方法将 post_id 和 user_id 保存在评论表中(我需要它来检索用户编写的所有评论以显示它)
该应用程序有用户(身份验证 - 设计)、帖子(由用户发布 - 但我不确定这对我来说是否重要)和评论(在帖子上,由用户发布)。
评论表有一个 post_id,一个 body,还有一个 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| %> ?)
谢谢!