2015-04-18 36 views
0

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

Rails的版本:4.2.0

操作系统:Windows 7

我有3种活动记录模式。 (用户,POST和评论)与

用户

has_many :posts 
has_many :comments 

邮政

belongs_to :user 
has_many :comments 

评论

belongs_to :user 
belongs_to :post 

Ñ如果我(登录用户)想要从帖子的展示页面创建评论,则为ow。我将如何将帖子的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'] 

这感觉马虎,这是正确的方式还是有一个更简单的方法?

回答

0

您可以使用嵌套的资源:

resources :posts 
    resources :comments 
end 

您的链接会去new_post_comment_path(@post)

里面你CommentsController,你将有机会获得params[:post_id]从路径创建您的评论。

另一个选择是使用表单对象(非ActiveRecord支持的模型),但这听起来像您的用例矫枉过正。