2011-03-03 20 views
0
<% form_for [commentable, Comment.new], :action => 'create', :remote => false do |f|%> 
<%=f.hidden_field :commentable_id, :value=> commentable.id %><br/> 
<%=f.hidden_field :parent_id, :value=>1 %><br/> 

和控制器:Rails 3中的form_for行動使用參數

def create(commentable) 
@commentable = commentable.find(params[:comment][:commentable_id]) 

如何我可以通過commentable類型在我for_for創建操作? 謝謝。

+0

我想你需要重塑你的問題,如果你想進一步的協助,你可以分享更多關於你的代碼? – tommasop

+0

在你的控制器中,嘗試'@commentable = Commentable.create(params [:comment] [:commentable_id])' –

回答

1

您需要使用

commentable.class 

沿着你已經沒有可以使用的一個隱藏字段行:在控制器

<%=f.hidden_field :commentable_type, :value=> commentable.class %><br/> 

然後:

@commentable = Object.const_get(params[:comment][:commentable_type]).find(params[:comment][:commentable_id]) 
+0

謝謝,但我如何傳遞我的可評論對象來創建操作? –

+0

爲什麼要傳遞整個對象?您可以傳遞一個id並稍後獲取對象。 –

0

你不不需要明確傳遞對象給你在控制器中創建方法,如果你有可評論的模型:

def create 
    @commentable = Commentable.find(params[:comment][:commentable_id]) 
    #more code 
end 

註釋大寫C中的可註釋。

+0

當然,但我使用acts_as_commentable_with_threading,而Commentable類不存在。 –