2010-09-17 49 views
1

尝试在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 |%>?)

谢谢!

回答

4

要设置非常类似的东西,我用以下形式:

<%= form_for [:place, @comment] do |f| %> 
    #form fields here 
<%= end %> 

然后在评论控制器:

def create 
    @post = Post.find(params[:post_id]) 
    @comment = @post.comments.build(params[:comment]) 
    @comment.user = User.find(current_user.id) 

    respond_to do |format| 
    if @comment.save 
    format.html { redirect_to(@comment.post, :notice => 'Comment was successfully created.') } 
    else 
    format.html { render :action => "new" } 
    end 
end 

这应该正确地构建协会希望!就像旁边一样,你的意思是要将评论嵌套在你的路线中的用户之下吗?如果你只是想一个个人资料页上显示的所有用户的评论,你可以这样做:

<p> 
    <b>Comments</b> 
    <% if @user.comments.empty? %> 
    No comments to display yet... 
    <% else %> 
    <% @user.comments.each do |comment| %> 
     <p> 
     <%= link_to "#{comment.post.title}", post_path(comment.post_id) %>, <%= comment.created_at %> 
     <%= simple_format comment.content %> 
     </p> 
    <% end %> 
    <% end %> 
</p> 

希望一些帮助!

+0

非常感谢,它帮助我很多! – benoitr 2010-09-17 08:42:27

相关问题