开发者

habtm multiple times with the same model

I am trying to model a publications. A publication can have multiple authors and editors. Since it is possible that one person is an author of one publication an开发者_C百科d an editor of another, no separate models for Authors and Editors:

class Publication < ActiveRecord::Base
  has_and_belongs_to_many :authors, :class_name=>'Person'
  has_and_belongs_to_many :editors, :class_name=>'Person'
end

The above code doesn't work, because it uses the same join table. Now I now that I can specify the name of the join table, but there is a warning in the API documentation is a warning about that which I don't understand:

:join_table: Specify the name of the join table if the default based on lexical order isn’t what you want. WARNING: If you’re overwriting the table name of either class, the table_name method MUST be declared underneath any has_and_belongs_to_many declaration in order to work.


It means that if class Publication is linked to a table with no standard name, example "my_publications":

class Publication < ActiveRecord::Base
  set_table_name "my_publication"
end 

The set table name should be put behind the habtm declaration for this to work:

class Publication < ActiveRecord::Base
  has_and_belongs_to_many :authors, :class_name=>'Person'
  has_and_belongs_to_many :editors, :class_name=>'Person'
  set_table_name "my_publication"
end


I'd generally consider this a case where you want to use has_many :through.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜