Calling a default record for a has_many association

I have a Shop model that has_many Zones (a Zone assigns different
pricing to products). I want to save a default Zone for a Shop. This
is what I have in my Shop class:

has_one :default_zone, :class_name => “Zone”

After that, however, I am a bit lost. I know I can manually set
shop.default_zone_id to a zone.id, but I would imagine a better system
of doing this exists.

Thanks,
Angelo, a desperate man

Hiya,

Not sure what you are after really but your solution seems okay to me.
If you are wondering how to then update it then:

Check here:
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#M001834

You can do things like:

build a default zone (doesn’t auto-save)

shop.build_default_zone(:name => ‘Zone1’)

create a default zone (auto-saves)

shop.create_default_zone(:name => ‘Zone2’)

or assign an existing zone:

zone = Zone.find(3)
shop.default_zone = zone

That any help?

Luke

I tried different variations of what you posted, and unfortunately,
none of them worked.

Both shop.build_default_zone and shop.create_default_zone create a
Zone record with the Shop ID correctly saved, but the Shop’s
default_zone_id column isn’t updated; shop.default_zone_id remains
blank.

This is basically what I have in seeds.rb:

shop = Shop.new
shop.name = “Sample”
shop.save

zone = shop.build_default_zone
zone.name = “Default”

shop.save

I attempted adding “shop.default_zone = Zone.first” at the end of
seeds.rb, but, again, it did not work.

Any ideas? Perhaps I’m ordering my saves/builds incorrectly? I can’t
get this seemingly simple thing to work.

Thanks for your help,
Angelo