为来自不同模型的表单重新填充提供数据

时间:2012-07-12 21:35:03

标签: ruby-on-rails-3 activemodel

所以我在这里遇到一个棘手的问题我不知道如何解决。

  1. 我有一个提供者模型has_many:education_affiliations
  2. EducationalAffiliation belongs_to:institution&属于 :提供商
  3. 我的数据库中有大约9000所大学,所以我使用方便的rails3-jquery-autocomplete宝石给我提前输入支持。这一切都很有效 - 最重要的是,我正在使用cocoon来支持在提供者编辑表单中嵌套:educational_affiliations表单。

    所以这就是问题所在 - 这非常适合提交新的联盟记录,(我正在使用一些jquery在:education_affiliations_attributes对象上设置:institution_id,效果很好)

    但是当我稍后再次编辑时,当然不会填充:institution_name,因为它不是:education_affiliations模型的一部分,它位于:机构模型中。

    以下是我刚刚尝试过的:education_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的机构错误 - 但是当我打开一个调试器时陈述,模型似乎知道机构_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
    

1 个答案:

答案 0 :(得分:0)

尝试以下方法来定义属性,而不是虚拟属性方法:

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