简体   繁体   中英

Active Record Query to get optional has_one

I am using Rails 3.2 and have the following and would like to load all the site placements with their native_ad_placement and sites. A NativeAdPlacement is also optional so could be nil. How would I do this?

class Site < ActiveRecord::Base
  has_many :site_placements
end

class SitePlacement < ActiveRecord::Base
  has_one :native_ad_placement
  belongs_to :site
end

class NativeAdPlacement < ActiveRecord::Base
  belongs_to :site_placement
end

You don't have to do anything - has_one is optional by default. If you're getting an error, check for any presence validations which could throw these.

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