我有文章模型,应该有一个画廊,每个画廊应该有许多图片。文章-画廊,画廊-图片模型之间的关联正常工作,但我不知道我做错了什么文章-图片协会。我把我的密码附在下面。
Article.rb模型
class Article < ActiveRecord::Base
belongs_to :gallery
has_many :pictures, through: :galleries
endGallery.rb模型
class Gallery < ActiveRecord::Base
has_many :pictures, dependent: :destroy
has_many :articles
endPicture.rb模型
class Picture < ActiveRecord::Base
belongs_to :gallery
has_many :articles, through: :galleries
endSchema.rb
ActiveRecord::Schema.define(version: 20150829181617) do
create_table "articles", force: :cascade do |t|
t.string "title"
t.text "content"
t.integer "author_id"
t.integer "language_id"
t.integer "category_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "gallery_id"
end
add_index "articles", ["gallery_id"], name: "index_articles_on_gallery_id"
create_table "galleries", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "pictures", force: :cascade do |t|
t.string "image"
t.integer "gallery_id"
t.string "image_file_name"
t.string "image_content_type"
t.integer "image_file_size"
t.datetime "image_updated_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
end发布于 2015-08-29 19:35:36
大卫的答案是正确的,belongs_to确实适用于Rails 4中的through关联。
class Article < ActiveRecord::Base
belongs_to :gallery
has_many :pictures, through: :gallery # not :galleries
end需要记住的是,through的has_one或has_many部分指的是关联,而不是另一个模型。当你做更复杂的联想时,这一点很重要。
发布于 2015-08-29 19:44:08
在Rails 4中,您肯定可以声明一篇文章:
belongs_to :gallery
has_many :pictures, :through => :gallery..。那张照片..。
belongs_to :gallery
has_many :articles, :through => :gallery..。允许你做这两件事:
@picture.articles..。还有..。
@article.galleries..。将这两种查询作为单一查询执行,并通过图库表连接起来。
https://stackoverflow.com/questions/32289621
复制相似问题