我是Rails的新手并且有问题。我有三张桌子:书籍,作者,书籍_作者。在我看来,我想显示两列。首先应该显示作者的姓名,第二个应该是作者写过小数的所有书籍。在我的books_authors表中,外键属于书籍和作者表中的主键。我的架构:
ActiveRecord::Schema.define(version: 20150709110928) do
create_table "authors", force: :cascade do |t|
t.string "name"
t.string "surname"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "authors_books", id: false, force: :cascade do |t|
t.integer "author_id"
t.integer "book_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "authors_books", ["author_id"], name:
"index_author_books_on_author_id"
add_index "authors_books", ["book_id"], name:
"index_author_books_on_book_id"
create_table "books", force: :cascade do |t|
t.string "title"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
和模型看起来像:
class Author < ActiveRecord::Base
has_many :authors_books
has_many :books, through: :authors_books
end
class Book < ActiveRecord::Base
has_many :authors_books
has_many :authors, through: :authors_books
end
我怎么能这样做?
答案 0 :(得分:1)
在模型authors_book中,你应该这样做
class AuthorsBook < ActiveRecord::Base
belongs_to :author
belongs_to :book
end
authors_books表中的每个条目都有author_id和books_id,这些条目包含多对多的关联。 现在当你做这件事时
@author.books
它将获取该作者撰写的所有书籍。
您可以轻松浏览这些图书并进行展示。
答案 1 :(得分:1)
我认为你应该稍微修改一下代码。我知道有两种方法可以实现多对多关联:
如果您想使用中间联接表&#39; authors_books&#39;,您应该使用has_and_belongs_to_many,但在这种情况下,您无法逐个访问authors_books,因为没有关于它的模型。
如果要将一些数据或信息存储到intermedidate连接表中,则应通过rails generator cmd创建模型,如$ rails g model AuthorBook somedata:integer
,并使用has_many through
。最后,删除&#39; authors_books&#39;表。代码如下:
class Author < ActiveRecord::Base
has_many :authorbooks
has_many :books, through: :authorbooks
end
class Book < ActiveRecord::Base
has_many :authorbooks
has_many :authors, through: :authorbooks
end
class Authorbook < ActiveRecord::Base
belongs_to :books
belongs_to :authors
end
答案 2 :(得分:0)
Many-to-Many association in rails can be achieve through,
has_many:_______ ; through:______
Ex: Physicians has many patients through appointments.Also, physicians has many appointments.
Patients has many physicians through appointments. Also, here patients has many appointments.
Here the common entity is appointments. So DHH, has implemented many-to-many like this way.
physicians
has_many :appointments
has_many :patients, through: :appointments
patients
has_many :appointments
has_many :physicians, through: :appointments
appointments
belongs_to :physicians
belongs_to :patients
希望它会有所帮助。