On 9/13/11 5:17 PM, Randy Regnier wrote:
On 09/13/2011 03:34 PM, Jesse wrote:
On 9/13/11 1:22 PM, Randy Regnier wrote:
I have a question about how best to model a pair of
properties/attributes in Rails3. The generic "models" are:
class Foo < ActiveRecord::Base
end
class Bar < ActiveRecord::Base
end
I want Foo to have two associations with Bar, along the lines of
'has_one' for each association, where I can work with each, as in
bar1 and bar2. 'has_many' would work, but it would be extra work to
have to fish the correct one out of the array, and isn't as elegant
a way to model the relationships.
Thanks
Randy
I suppose that it could be done with a has_one relationship repeated
as such
class Foo < AR::B
belongs_to :bar1, class_name => "Bar", :foreign_key => "bar1_id"
belongs_to :bar2, class_name => "Bar", :foreign_key => "bar2_id"
end
Mind you this is not a very elegant way of doing it, but it is
adhering to KiSS principles.
On the Bar end of things, how should the relationship play out?
Should it only be able to be associated to one Foo?
Also are do bar 1 and bar 2 behave differently or have any
characteristic that distinguish them. In other words, are all bar1's
always going to be bar1's? if so you can do a normal has many
relationship with a limit of 2 children and then scopes on the bar
model to make up the difference.
Jesse
Thanks.
On the Bar end, it would only be associated with the one Foo, yes.
You could go the STI route and give each bar its own sub class
class Bar < AR::B
end
class BarOne < Bar
belongs_to :foo
end
class BarTwo < Bar
belongs_to :foo
end
and add the attribute type to Bar
then your Foo class could be
class Foo < AR::B
has_one :bar_one, :dependant => :destroy
has_one :bar_two, :dependant => :destroy
end
with attributes of
the :dependant => :destroy will allow the two bars to be destroyed when
the foo is destroyed.
While a little more work than my original suggestion this will be far
more elegant as you can easily deploy more bars if needed. Also it is
technically more correct as it would seem that 2 bars really belongs to
one foo as deleting the foo should delete the bars, whereas the other
way would make the Bars the parents of the Foo.
bar1 and bar2 would have different values for their respective
properties, but that is about all. Well, I guess if a Foo got removed,
then so should both of its Bars, but I think I've seen how to do that
part.
Randy
--
You received this message because you are subscribed to the Google Groups "Ruby on
Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en.