2012-07-23 190 views
0

因此,我有一个相当典型的博客应用程序,包含帖子和评论。通过Rails中另一个对象的显示动作创建一个对象

每个评论都属于一个职位 一篇文章可以有很多评论。

基本上我想为帖子的显示操作添加注释的表单,而在评论模型中没有attr_accessible下的post_id。

在我的职位控制器我有:

def show 
    @post = Post.find(params[:id]) 
    @poster = "#{current_user.name} #{current_user.surname} (#{current_user.email})" 
    @comment = @post.comments.build(poster: @poster) 
    end 

我不完全知道我应该在评论控制器做(我不相信,上面的代码是正确的或者如果我诚实)。目前,我有:

def create 
    @post = Post.find(params[:post_id]) 
    @comment = @post.comments.build(params[:post]) 
    if @comment.save 
    redirect_to @post, notice: "Comment posted" 
    else 
    redirect_to @post, error: "Error!" 
    end 
end 

我的路线:

resources :comments 

    resources :posts do 
    resources :comments 
    end 

终于形式:

<%= form_for @post.comments.build do |f| %> 
     <%= f.label :content, "WRITE COMMENT" %> 
     <%= f.text_area :content, rows: 3 %> 
     <%= f.hidden_field :post_id, value: @post.id %> 
     <%= f.submit "Post" %> 
    <% end %> 

这里的问题是,我没有通过我的POST_ID从方式将帖子控制器的操作显示给评论控制器的创建操作。任何帮助深表感谢。先谢谢你!

回答

4

你的帖子控制器看起来不错......但假设你的路径看起来像

resources :posts do 
    resources :comments 
end 

那么你CommentsController#创建应该/可能看起来像:

def create 
    @post = Post.find(params[:post_id]) 
    @comment = @post.comments.build(params[:comment]) 
    if @comment.save 
    redirect_to @post, notice: "Comment posted" 
    else 
    redirect_to @post, error: "Error!" 
    end 
end 

而且您的表格:

<%= form_for [@post, @comment] do |f| %> 
    <%= f.hidden_field :poster, value: @poster %> 
    <%= f.label :content, "WRITE COMMENT" %> 
    <%= f.text_area :content, rows: 3 %> 
    <%= f.submit "Post" %> 
<% end %> 
+0

打我1分钟:) – 2012-07-23 18:24:50

+0

@YuriyGoldshtrakh我很快就像忍者! – 2012-07-23 18:38:45

+0

这看起来像我在找什么,但目前它告诉我它无法在创建操作中找到post_id?我会坚持我的路线和查看以防万一这是问题... – TangoKilo 2012-07-23 18:39:19

0

您的展示帖子的网址应该像post/show/(:id)
现在,在评论表单中,您可以放置​​一个隐藏字段,其值为params[:id]

hidden_field(:post_id, :value => params[:id]) 

当您提交表单时,可以使用隐藏字段获取post_id的值。

def create 
     @comment = Comment.new(params[:comment]) 
     @comment.post_id = params[:post_id] 

     if @comment.save 
      flash[:notice] = 'Comment posted.' 
      redirect_to post_path(@comment.post_id) 
     else 
      flash[:notice] = "Error!" 
      redirect_to post_path(@comment.post_id) 
     end 
    end 
0

我会假设你的岗位模型的has_many意见和评论belongs_to的发布

比你在你的路由文件,你可以做这样的事情

resources :posts do 
    resources :comments 
end 

这会给你一个网址舍姆等

/posts /:post_id/comments,允许你总是有post_id的评论parrent

相关问题