2012-07-12 65 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