Rails如何为关联设置预定义的属性值

时间:2013-10-04 06:14:07

标签: ruby-on-rails activerecord

我有一个类似

的模型
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"

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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 了解更多文档。 看看这两种方法,并应用哪种更适合你。

答案 2 :(得分:-1)

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

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

然后在关系上使用方法代替create!