1

我有一个模型

class CqmExternalId < ActiveRecord::Base
        set_table_name :cqm_external_id
        has_many :ipp_measure_ids, :class_name => "CqmMeasureId", :foreign_key => "cqm_external_id", :conditions => [" name = 'IPP'"]
        has_many :numer_measure_ids, :class_name => "CqmMeasureId", :foreign_key => "cqm_external_id", :conditions => [" name = 'NUMER'"]
        has_many :denom_measure_ids, :class_name => "CqmMeasureId", :foreign_key => "cqm_external_id", :conditions => [" name = 'DENOM'"]
        has_many :denex_measure_ids, :class_name => "CqmMeasureId", :foreign_key => "cqm_external_id", :conditions => [" name = 'DENEX'"]
end

class CqmMeasureId < ActiveRecord::Base
        set_table_name :cqm_measure_id
        belongs_to :cqm_external, :class_name => "cqm_external", :foreign_key => "cqm_external_id"
end

如何进行ipp_measure_ids关联以在其上插入默认值create

 c = CqmExternalId.first
 c.ipp_measure_ids.create!(:key=>"ABC-1234")  => #<CqmMeasureId id: 1, name:nil, key:"ABC-1234>"

 # I want the name attribute to be initialized automatically as "IPP"
4

3 回答 3

1

您可以使用 before_save

class CqmMeasureId < ActiveRecord::Base
        set_table_name :cqm_measure_id
        belongs_to :cqm_external, :class_name => "cqm_external", :foreign_key => "cqm_external_id"

   before_save :add_default_name

   def add_default_name
     self.name = 'IPP' if self.name.blank?
   end
end
于 2013-10-04T06:21:01.603 回答
1

如果您一直需要完成您的应用程序,那么请添加迁移以将默认值设置为列。

change_column :ipp_measure_ids, :name, :string, :default => 'IPP'

在这种方法中,您无需自动编写 ant 事物,名称列将保存为“IPP”

如果将来有可能在这种情况下更改值,最好在模型中使用 before save 方法,例如

 before_save :save_default_name_value

   def save_default_name_value
     self.name = 'IPP' if self.name.blank?
   end

但请确保每次保存(创建、更新)它都会调用此函数。如果您仅在创建时需要,请使用after_create方法。

另请查看http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html 以获取更多文档。看看这两种方法并应用哪种方法更适合您。

于 2013-10-04T06:46:03.637 回答
-1

由于您的所有关系都具有相同的类,因此您将编写一个包装器方法来在您的CqmExternalId类上执行此任务。就像是:

def create_ipp_measure_id(attrs)
  data = attrs.merge({:name => "IPP"})
  ipp_measure_ids.create!(data)
end

然后使用方法而不是create!关系。

于 2013-10-04T06:17:22.447 回答