[Ruby] Associations problem
Laurel Fan
laurel.fan at gmail.com
Sat Jan 6 08:41:32 PST 2007
On 1/6/07, shaners becker <veganstraightedge at gmail.com> wrote:
> so i have three tables: subscribers, subscription_items and products
snipping the stuff that seems irrelevant to me:
> subscriber has_many subscription_items
> subscription_item has_many products
> products belongs_to subscription_item
(I'm assuming you typed the above two in backwards?, and you mean
subscription_item belongs_to product etc?)
> subscription_items belongs_to subscriber
>
> subscribers':
>
> subscription_items' schema:
> subscriber_id
> product_id
>
> products' schema:
> title
>
> how do i refer to the title of a subscription_item of this user?
> is this a case for habtm or through?
You don't need an association just to refer to the title, you can do
something like:
subscriber.subscription_items[0].product.title
If you want users to have a collection of products, I would use
through since your join table, subscription_items, is its own model
object with other data (the docs refer to this as a join model).
Something like:
class Subscriber
has_many :subscription_items
has_many :products, :through => :subscription_items
end
see the 'Association Join Model' section here:
http://www.rubyonrails.org/api/classes/ActiveRecord/Associations/ClassMethods.html
If you just want to collect the tittles of the products, you would
probably use something like:
subscriber.products.collect(&:title) (as far as I know, associations
are made to ActiveRecord objects, not to things like Strings, so I you
can't make a titles collection through associations)
--
Laurel Fan
http://blog.gorgorg.org
More information about the Ruby
mailing list