Ruby on rails 在两个表之间建立两个关联

Ruby on rails 在两个表之间建立两个关联,ruby-on-rails,activerecord,ruby-on-rails-3.2,associations,polymorphic-associations,Ruby On Rails,Activerecord,Ruby On Rails 3.2,Associations,Polymorphic Associations,我的项目中有一个奇怪的要求。实际上,我有两个表(用户、库)。我想访问具有一个或多个关联的图库表。主要目的是使用has\u-one关系获取用户的个人资料快照,并使用has\u-many关系获取个人上传的图片 最初我使用多态关联来解决这个问题(仅供参考,请查找下面的代码片段)。但我认为这不是解决这个问题的正确方法 有谁能解释一下如何有效地处理这个案件 class User < ActiveRecord::Base attr_accessible :name has_many :gala

我的项目中有一个奇怪的要求。实际上,我有两个表(用户、库)。我想访问具有一个或多个关联的图库表。主要目的是使用has\u-one关系获取用户的个人资料快照,并使用has\u-many关系获取个人上传的图片

最初我使用多态关联来解决这个问题(仅供参考,请查找下面的代码片段)。但我认为这不是解决这个问题的正确方法

有谁能解释一下如何有效地处理这个案件

class User < ActiveRecord::Base
  attr_accessible :name
  has_many :galaries, as: :imageable
  has_one :galary, as: :imageable
end

class Galary < ActiveRecord::Base
  attr_accessible :name
  belongs_to :imageable, polymorphic: true
end
class用户
您需要在
galaries
表中添加一列
user\u id
,以便将用户链接到galary(配置文件快照)

这将生成迁移:

class AddUserIdToGalaries < ActiveRecord::Migration
  def change
    add_column :galaries, :user_id, :integer
  end
end

可以通过作用域
具有一个关联来完成。虽然不是必需的,但您可以使用作用域定义在
有一个
中选择哪个
库。如果没有给出作用域,
有一个
将返回第一个匹配项

class User < ActiveRecord::Base
  attr_accessible :name
  has_many :gallaries
  has_one :gallery, -> { where primary: true }
end

class Gallery < ActiveRecord::Base
  #user_id, primary (boolean variable to select the gallery in has one association)
  attr_accessible :name
  belongs_to :user
end
class用户{where primary:true}
结束
类库
你的意思是,我需要保持多态性,并且有一个组合。使用类名等是否有其他选择?既然用户已经有了很多:galaries,那么类名将无法完全识别它,那么是否有其他选择,比如将类名放在has\u many etcCheck tihom的答案上。它会起作用,但效率不如这。因为他的建议会给这个问题增加更多的条件
User.first.galary
将导致查询搜索3列,而不是1列。@pramod如果这些没有回答您的问题,请发布您的备选答案。
class User < ActiveRecord::Base
  attr_accessible :name
  has_many :galaries, as: :imageable
  has_one :galary #profile snap
end

class Galary < ActiveRecord::Base
  attr_accessible :name
  belongs_to :imageable, polymorphic: true
  belongs_to :user #profile snap user
end
class User < ActiveRecord::Base
  attr_accessible :name
  has_many :gallaries
  has_one :gallery, -> { where primary: true }
end

class Gallery < ActiveRecord::Base
  #user_id, primary (boolean variable to select the gallery in has one association)
  attr_accessible :name
  belongs_to :user
end