简体   繁体   English

Rails关联跳过更新关联对象

[英]Rails association skip update associated object

class City<ActiveRecord::Base
  has_one :template, class_name:'TmplLocation'
  after_initialize :_init
  private
  def _init

    self.template = TmplLocation.find(18) if !self.template
  end
end

And that's what happens in console: 这就是控制台中发生的情况:

>Loc.first.template
  City Load (29.8ms)  SELECT `locations`.* FROM `locations` WHERE `locations`.`type` IN ('City') LIMIT 1
  TmplLocation Load (0.2ms)  SELECT `locations`.* FROM `locations` WHERE `locations`.`type` IN ('TmplLocation') AND `locations`.`location_id` = 23 LIMIT 1
  TmplLocation Load (34.8ms)  SELECT `locations`.* FROM `locations` WHERE `locations`.`type` IN ('TmplLocation') AND `locations`.`id` = ? LIMIT 1  [["id", 18]]
  SQL (0.2ms)  BEGIN
   (0.7ms)  UPDATE `locations` SET `location_id` = 23, `updated_at` = '2013-06-11 10:47:11' WHERE `locations`.`type` IN ('TmplLocation') AND `locations`.`id` = 18
   (41.4ms)  COMMIT

You see? 你看? It updates the TmplLocation so now it is constantly associated with this exact city. 它会更新TmplLocation,因此现在它一直与这个确切的城市关联。 I want only use the TmplLocation instance in this City How to skip update stage?? 我只想在此City中使用TmplLocation实例。如何跳过更新阶段?

You can try something like this 您可以尝试这样的事情

class City<ActiveRecord::Base
  has_one :template, class_name:'TmplLocation', :conditions => { :id => 18 }
end

For more options see this 有关更多选项,请参见此

guides.rubyonrails.org guides.rubyonrails.org

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM