2015-04-18 32 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支持的模型),但這聽起來像您的用例矯枉過正。