2013-12-18 35 views
9

有沒有辦法顯示simple_form視圖中的多態關聯?Simpleform中的多態關聯

到目前爲止,我已經得到了以下:

= simple_form_for(@chat, :html => { :class => "form-horizontal" }, :wrapper => "horizontal", defaults: { :input_html => { class: "form-control"}, label_html: { class: "col-lg-4" } }) do |f| 
    = f.error_notification 

    .form-inputs 
     = f.association :from_user 
     = f.association :to_user 
     = f.input :message 
     = f.association :chattable 

    .form-actions 
     = f.button :submit 

及以下型號:

class Chat < ActiveRecord::Base 
    belongs_to :from_user, :foreign_key => 'from_user_id', class_name: 'User' 
    belongs_to :to_user, :foreign_key => 'to_user_id', class_name: 'User' 
    belongs_to :chattable, polymorphic: true 

    validates :from_user, associated: true, presence: true 
    validates :message, presence: true 
end 

這將引發如下錯誤:

uninitialized constant Chat::Chattable 
+0

這看起來可能是一個包含問題。你能告訴我們聊天模式嗎? – Narfanator

+0

我沒有'chattable'模型。它是'多態的',它是'聊天表'的一部分 –

+0

等待。您的應用名稱是「Chat」還是您的模型?這可能是你的問題。嘗試重命名「聊天」類,然後「set_table_name」聊天「'。 – Narfanator

回答

5

通過多下襬,hawing和我們已經確定SimpleForm不會這樣做。

這就是爲什麼! (嗯,可能是爲什麼)

SimpleForm需要找出該關聯是什麼類。由於缺省情況是關聯名稱是該類的非大寫名稱,因此最終會尋找類「Chattable」,並且找不到它,這是您的錯誤來自哪裏。

好消息是,你需要做的就是將f.association :chattable行替換成你所需要的東西。 http://guides.rubyonrails.org/form_helpers.html#making-select-boxes-with-ease有你需要的信息來做到這一點「簡單的方法」 - 又名,與Rails窗體助手。

我的建議是有一個chattable_type的選擇框,以及一些JS,它可以隱藏該類型的選擇框的HTML。所以你會得到像

= select_tag(:chattable_type, ["Booth", "Venue"]) 

= collection_for_select(:chattable_id, Booth.all) 
= collection_for_select(:chattable_id, Venue.all) 
... 

不包括JS和CSS。查看上面鏈接的文檔以獲取實際的語法;我認爲我的一點點。

+0

非常感謝你的這一切和你的所有幫助! –

+2

沒問題!解決問題是有趣的東西,現在我更瞭解Rails的工作原理。 – Narfanator

7

我發現其他解決方案不需要JS操作,仍然可以使用簡單的表單輸入。 您可以使用輸入選擇ID和類型作爲選項值,以逗號分隔。

= f.input :chattable, collection: @chat.chattables, selected: f.object.chattable.try(:signature), 

然後在聊天模式:

def chattables 
    PolymorphicModel.your_condition.map {|t| [t.name, t.signature] } 
    end 

    def chattable=(attribute) 
    self.chattable_id, self.chattable_type = attribute.split(',') 
    end 

而在你PylymorphicModel

def signature 
    [id, type].join(",") 
    end 

請記住,如果你使用它們chattable添加到安全PARAMS。