Double has_many help

I'm a total newbie on this, and I'm learning at baby steps, I am really excited from what I've learned with Ruby on Rails, but I have hit a wall here, I hope someone can help me to figure this out.

I'm trying to implement what I think is a simple relation between 3 kinds of data: Machine, Kind, Product

- Machine can have many Kinds (I used HABTM and a join table, and used check boxes in the view, ready, no problems in here) - Product(s) must have one Kind (Used has_many and belongs_to, using a select_tag for the view, no trouble here)

Now what is giving me some headaches:

-Machine must list the Product(s) that share the same Kind <== How can I implement this? any suggestions or ideas?

I tried has_many => through, but it seems that I am misunderstanding the method.

class Machine < AR has_and_belongs_to_many :kinds has_many :products, :through => :kinds ??? end

All errors are very explicit telling me that I'm missing a column, but the thing here is, how can I call the same Kind on two different things, how can I call Products that have the same Kind as Machine?

Thank you. Roberto.

If you want to use has_many :through, the trouble with that is, it
expects a has_many, not a habtm association to go through.

so, you need to concretise your join tables to use it...

class Kind < AR end

class MachineKind < AR # attributes: id, machine_id, kind_id end

class Kind < AR has_many :machine_kinds has_many :kinds, :through => :machine_kinds end

class Machine < AR has_many :machine_kinds has_many :kinds, :through => :machine_kinds def products   kinds.map{|kind| kind.product}.uniq end end

the "products" method inside the Machine class should solve your other
issue, however don't try to use it like an association (ie trying to
run the method machine.products.build where machine is a Machine
instance, for example - this won't work)

It all depends what you want to do with products once you have them.

Julian.

Thank you for your answer Julian.

All your method is very clear, I'll be trying it as soon as possible (really tired right now) but in general, yes I was going for a Machine.products.find(:all) to list all possible Products compatible with Machine, and since both Machine and Product get the same Kind(from the same "kinds" table) I thought they were related in some way I just couldn't find out how to do that.

Anyway, I'll try your suggestion, and dropping some lines here for more help. :wink:

Thank you very much. Regards.

Roberto.