2012-07-12 61 views
0

所以我有一個棘手的問題,我不知道如何解決。爲不同模型的表單重新填充數據提供

  1. 我有一個HAS_MANY提供者模型:educational_affiliations
  2. EducationalAffiliation belongs_to的:機構& belongs_to的 :供應商

我有我的數據庫中大約9000所大學,所以我使用的handy-丹迪rails3-jquery-autocomplete寶石給我輸入提前支持。這一切都很好 - 在TOP中我使用了cocoon來支持在提供者的編輯表單中嵌入:educational_affiliations表單。

所以這裏的地方的問題來 - 這提交新的合作記錄的偉大工程,(我使用一些jQuery來設置:institution_id上:educational_affiliations_attributes對象,偉大工程)

當我稍後返回編輯它,當然::institution_name未填充,因爲它不是:educational_affiliations模型的一部分,它位於:院校模型中。

這裏就是我只是想在我的:educational_affiliations,我認爲是正確的解決方案:

class EducationalAffiliation < ActiveRecord::Base 
    attr_accessible :degree, :graduation_year, :honors, :institution_name, :institution_id, :provider_id 
    belongs_to :institution 
    belongs_to :provider 

    # attr_accessor :institution_name 

    validates :institution_id, :graduation_year, :provider_id, :degree, presence: true 

    def institution_name 
    Institution.find(institution_id).name 
    end 

end 

(我有它的工作使用attr_accessor中保存,但我曾評論它現在)

所以,當我使上述編輯視圖,我得到一個的ActiveRecord :: RecordNotFound:沒有ID找不到機構錯誤 - 但是當我打開該聲明調試器,該模型似乎要知道institution_id ...所以很困惑,爲什麼它不接受。

我只是以最糟糕的方式做到這一點嗎?我想有一個愚蠢的解決方案.. :)

這裏的部分,需要填寫姓名:

.nested-fields 
    = f.input :institution_name, url: autocomplete_institution_name_data_path, as: :autocomplete, :input_html => {:id_element => '#provider_educational_affiliations_institution_id'} 
    = f.input :institution_id, as: :hidden 
    = f.input :provider_id, as: :hidden, input_html: { value: current_provider.id } 
    = link_to_remove_association "Remove Degree", f 

回答

0

取而代之的是虛擬屬性的方法,請嘗試以下定義屬性:

delegate :name, :name=, :to => :institute, :prefix => true 
+0

這很好,我還不熟悉委託功能 - 最後一個問題,名稱現在正確填充,但提交時我得到一個UnknownAttributeError - 我可以在更新發生之前刪除屬性,但寧願有該模型只是「得到」它..你有一個解決方案的建議? – MBHNYC 2012-07-16 16:08:30

+0

啊!已解決<< delegate:name,:name =,:to =>:institute,:prefix => true。委託安裝人員進行救援。是的,這太酷了,沒有更好的記錄。 – MBHNYC 2012-07-16 20:41:37

+0

真棒,我會更新答案,以包括setters以及。 – 2012-07-17 00:11:21