如果要访问连接表记录,则必须使用has-many-through
关系重新创建连接表。这里有一个很好的指导,以及has-many-through
和has-and-belongs-to-many
之间的区别,在这里:http://railscasts.com/episodes/47-two-many-to-many。
你需要创建一个类似以下内容来创建连接表一个新的迁移:
class Authorships < ActiveRecord::Migration
def change
create_table :authorships do |t|
t.belongs_to :book, index: true
t.belongs_to :author, index: true
t.timestamps null: false
end
add_foreign_key :authorships, :books
add_foreign_key :authorships, :authors
end
end
其中“的著者”可以是任何名称您认为适合的连接表(或“BookAuthors”如果你会想坚持)。
作为一个简单的例子,你的模型可能看起来像以下:
class Book < ActiveRecord::Base
has_many :authorships
has_many :authors, through: :authorships
end
class Author < ActiveRecord::Base
has_many :authorships
has_many :books, through: :authorships
end
class Authorship < ActiveRecord::Base
belongs_to :book
belongs_to :author
end
您可以添加额外的列到连接表并访问他们根据需要,与authorship_ids
一起,和Author.first.books
/Book.first.authors
一旦他们”重新添加。
希望有用!
你不能。 'has_and_belongs_to_many'使用join _table_,而不是join _model_。你想在连接模型中使用'has_many:through'。 – Substantial 2015-02-23 18:46:23