Activerecord RubyonRails将一个模型的对与第二个模型相关联

Activerecord RubyonRails将一个模型的对与第二个模型相关联,activerecord,associations,Activerecord,Associations,我正在构建一个rails应用程序,其中有模型、用户、图像和图像对。我希望每个图像对有2个图像,分别命名为:before\u image和:after\u image 因此: 用户有多个图像多对一 用户拥有多对多对图像 图像可能只有一个图像对 图像对总是有两个图像 我的一切正常,除了我不能打@image.image\u-pair。我得到: PG::UndefinedColumn:错误:列映像\u对。映像\u id不存在 我如何设置它,以便从它的图像中获取图像对 schema.rb删除了一些不相关的

我正在构建一个rails应用程序,其中有模型、用户、图像和图像对。我希望每个图像对有2个图像,分别命名为:before\u image和:after\u image

因此:

用户有多个图像多对一 用户拥有多对多对图像 图像可能只有一个图像对 图像对总是有两个图像 我的一切正常,除了我不能打@image.image\u-pair。我得到:

PG::UndefinedColumn:错误:列映像\u对。映像\u id不存在

我如何设置它,以便从它的图像中获取图像对

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

image.rb

image_pair.rb


您可以将一个名为image\u id的字段添加到image\u对中,该字段指向原始图像id。或者,如果您想通过name before\u image调用它,可以将before\u图像重命名为image\u id并添加别名或方法

def before_image
  self.image_id
end

我至少会把最后两个改成一个。第一个也是:在你的形象之前。。。等
class Image < ActiveRecord::Base
  belongs_to :user
  has_one :image_pair
end
class ImagePair < ActiveRecord::Base
  belongs_to :user
  belongs_to :before_image, :class_name => "image"
  belongs_to :after_image, :class_name => "image"
end
def before_image
  self.image_id
end