2012-07-23 89 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