在两个表之间建立两个关联

时间:2014-11-04 07:07:02

标签: ruby-on-rails activerecord ruby-on-rails-3.2 associations polymorphic-associations

我的项目有一个奇怪的要求。实际上,我有两个表(用户,画廊)。我想访问带有has_one和has_many关联的画廊表。主要目的是通过使用has_one关系获取用户的配置文件捕捉,并使用has_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

2 个答案:

答案 0 :(得分:1)

您需要在user_id表格中添加一列galaries,以便将用户链接到小组(个人资料快照)。

rails generate migration add_user_id_to_galaries user_id:string 

这将生成迁移:

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

然后运行rake db:migrate


立即转到我们的模型:

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

答案 1 :(得分:0)

可以使用范围has_one关联来完成。虽然不是必需的,但您可以使用范围定义gallery中选择的has_one。如果没有给出范围,has_one将返回第一个匹配。

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