如何通过rails应用程序传递参数?

时间:2015-04-18 03:14:50

标签: ruby-on-rails ruby ruby-on-rails-4 activerecord

我正在使用

  

Rails版本:4.2.0

     

操作系统:Windows 7

我有3个Active记录模型。 (用户,帖子和评论)

用户

has_many :posts
has_many :comments

发表

belongs_to :user
has_many   :comments

注释

belongs_to :user
belongs_to :post

现在,如果我(已登录的用户)想要从帖子的显示页面创建评论。我如何将帖子的ID传递给评论的创建动作?

我能想到的唯一方法就是这样:

发布的显示页面

link_to 'Create comment', new_comment_path(post_id: @post.id)

评论的新页面(在表格内)

hidden_field_tag ':post_id', params[:post_id]

评论的创建动作

@comment = current_user.comments.build(comment_params)
@comment.post_id = params[':post_id']

这感觉很草率,这是正确的方式还是有更简单的方法?

1 个答案:

答案 0 :(得分:0)

您可以使用嵌套资源:

resources :posts
  resources :comments
end

您的链接将转到new_post_comment_path(@post)

在您的CommentsController中,您可以从路径中访问params[:post_id]来创建评论。

另一种选择是使用表单对象(非ActiveRecord支持的模型),但这对您的用例来说听起来有点过分。

相关问题