Вопрос

So, I have a STI organization that goes like this:

class Parent
end

class Son < Parent
end

class Daughter < Parent
end

But each child has a HBTM(has_and_belongs_to_many) relation with a different model. Let's call it Chick and Dude, so it would look like this:

class Parent
end

class Son < Parent

  has_and_belongs_to_many :chicks

end

class Daughter < Parent

  has_and_belongs_to_many :dudes

end

Where should I declare the relation-ships? Both at the Parent model? Does it need any additional options? Will Rails make the column null when it should be by it self?

I've been looking for an answer for this but couldn't find it, maybe because it is just too dumb.


EDIT

As mentioned by Peter Alfvin, HBTM relations must come along with an auxiliary join table. Which means that this configuration would require two join tables.

But, I did not find any documentation about the nomenclature that should be used in this very specific example.

The join table should include the name of the database table 'parents' or the model's name 'daughters'?

The same problem occur with the id column referencing the STI, should it be named after the database table or the model?

Это было полезно?

Решение 2

For what I could understand, it works like each of the STI sub classes had it's own table (although in the database they use the same, named after it's parent). So, in the HBTM join table, you should use ID and table name referent to the "illusionary" child table. The migration look's like this:

create_table :daughters_dudes, id: false do |t|
  t.belongs_to :daughter
  t.belongs_to :dude
end

Другие советы

I believe you have it expressed correctly. You wouldn't want it at the parent level because each subclass is associated with a different class.

I don't know what you mean by "make the column null". There is no column in the referencing tables for a HABTM relationship. The HABTM association assumes a separate join table for each HABTM model pair and records are only created in that table when a relationship is established between instances of the associated models.

See http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association for a description of the join table.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top