简体   繁体   中英

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. I want only use the TmplLocation instance in this City How to skip update stage??

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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