【问题标题】:Buid two associations between two tables在两个表之间建立两个关联
【发布时间】:2023-03-30 04:35:02
【问题描述】:

我的项目中有一个奇怪的要求。实际上,我有两张桌子(用户,画廊)。我想使用 has_one 和 has_many 关联访问画廊表。主要目的是通过has_one关系获取用户的头像,通过has_many关系获取个人上传的图片。

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

有人能解释一下如何以有效的方式处理这种情况吗?

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

【问题讨论】:

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


    【解决方案1】:

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

    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
    

    【讨论】:

    • 你的意思是,我需要维护多态和 has_one 的组合。使用 class_name 等有什么替代方法吗?
    • 既然用户 has_many :galaries 已经存在,那么类名将无法识别它
    • 当然,那么有没有其他选择,比如将 class_name 放在 has_many 等处
    • 检查 tihom 的答案。它会起作用,但它的效率不如这个。因为他的建议将为查询添加更多条件。 User.first.galary 将导致查询搜索 3 列而不是 1 列。
    • @pramod 如果这些没有回答您的问题,请发布您的替代答案。
    【解决方案2】:

    可以通过作用域has_one 关联来完成。尽管不是必需的,但您可以使用范围定义在has_one 中选择哪个gallery。如果未指定范围,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
    

    【讨论】:

      猜你喜欢
      • 2019-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-10
      • 1970-01-01
      • 1970-01-01
      • 2020-01-01
      • 2015-10-29
      相关资源
      最近更新 更多