Ruby on Rails将一个模型的对与第二个模型相关联

时间:2015-05-29 19:16:26

标签: activerecord associations

我正构建一个rails应用,其中包含模型usersimagesimage_pairs。我希望每个image_pair都有2个images,名为:before_image:after_image

所以:

  • users有许多images(多对一)
  • users有许多image_pairs(多对一)
  • images可能只有一个image_pair
  • image_pairs总是有2 images

我有一切正常,除了我无法致电@image.image_pair。我明白了:

PG::UndefinedColumn: ERROR: column image_pairs.image_id does not exist

如何进行设置以便我可以从image_pair获得image

schema.rb (删除了一些不相关的字段)

create_table "image_pairs", force: true do |t|
  t.integer  "before_image_id"
  t.integer  "after_image_id"
end

add_index "image_pairs", ["before_image_id"], name: "index_image_pairs_on_before_image_id", using: :btree
add_index "image_pairs", ["after_image_id"], name: "index_image_pairs_on_after_image_id", using: :btree
add_index "image_pairs", ["user_id"], name: "index_image_pairs_on_user_id", using: :btree

create_table "images", force: true do |t|
  t.integer  "user_id"
  t.integer  "image_pair_id"
end

add_index "images", ["image_pair_id"], name: "index_images_on_image_pair_id", using: :btree
add_index "images", ["user_id"], name: "index_images_on_user_id", using: :btree

create_table "users", force: true do |t|
  t.string   "name"
end

user.rb

class User < ActiveRecord::Base
  has_many :images, dependent: :destroy
  has_many :image_pairs, dependent: :destroy
end

image.rb

class Image < ActiveRecord::Base
  belongs_to :user
  has_one :image_pair
end

image_pair.rb

class ImagePair < ActiveRecord::Base
  belongs_to :user
  belongs_to :before_image, :class_name => "image"
  belongs_to :after_image, :class_name => "image"
end

1 个答案:

答案 0 :(得分:0)

您可以向image_pairs添加一个名为image_id的字段,该字段指向原始图片ID。或者将before_image重命名为image_id,如果要通过名称before_image调用它,则添加别名或方法。

def before_image
  self.image_id
end