Rails:在DB中的注释表中存储帖子ID

时间:2012-02-26 05:20:56

标签: ruby-on-rails ruby database ruby-on-rails-3 associations

我有一个评论模型,我想在post_id部分的db中的注释表中存储我正在评论的post.id.到目前为止,我的注释控制器代码设置为

评论控制器

class CommentsController < ApplicationController 
  def create
    @comment = Comment.new(params[:comment])
    @comment.user_id = current_user.id
    *@comment.micropost_id = Micropost.find(params[:id])*
    @comment.save 
      respond_to do |format|
      format.html 
      format.js
    end
  end
end

@comment.micropost_id = Micropost.find(params[:id])这就是我现在所拥有的,但我不确定如何将其连接到表单以便接收post.id.表格是:

表格

<div class="CommentField">
<%= form_for @comment, :remote => true do |f| %>
<%= f.text_area :content, :class => "CommentText", :placeholder => "Write a Comment..." %>
<div class="CommentButtonContainer">
<%= f.submit "Comment", :class => "CommentButton b1" %>
</div>
<% end %>
</div>

我的一位朋友告诉我添加一个指向提交按钮的链接,将其连接到正确的路线以获取post.id,但我也不确定。我的路线目前是:

路线

  resources :microposts do
    resources :comments
  end

  match "/microposts/:id/comments" => "microposts#comments"

2 个答案:

答案 0 :(得分:1)

您只需在表单中添加隐藏的输入,例如

<%= form_for @comment, :remote => true do |f| %>


<input type="hidden" name="micropost_id" value="<%= params[:id] %>" />


<%= f.text_area :content, :class => "CommentText", :placeholder => "Write a Comment..." %>
<div class="CommentButtonContainer">
<%= f.submit "Comment", :class => "CommentButton b1" %>
</div>
<% end %>

并在控制器中:

class CommentsController < ApplicationController 
  def create
    @comment = Comment.new(params[:comment])
    @comment.user_id = current_user.id
    @comment.micropost_id = params[:micropost_id]

答案 1 :(得分:1)

使用嵌套表单结帐... http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

或只是使用

form_for [@post, @comment] do |f|
...

你的路线也过于复杂了

resources :microposts do
  resources :comments
end

是您完成此工作所需的一切(即忘记其他match行。尝试运行rake routes以查看嵌套路由为您提供的所有可爱网址。

在您的控制器中,首先查找Micropost

def create
  @micropost = Micropost.find(params[:micropost_id])
  @comment = @micropost.comments.build(params[:comment])
  ..

有意义吗? API文档http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

中有一个冗长但很好的介绍