【问题标题】:how to write a condition for has_many association that joins two tables?如何为连接两个表的 has_many 关联编写条件?
【发布时间】:2014-04-29 22:30:10
【问题描述】:

我有一个用户模型:

class User < ActiveRecord::Base
  has_many :profile_label_values
  belongs_to :company
end

个人资料标签值模型:

class profileLabelValue < ActiveRecord::Base
  belongs_to :profile_label
  belongs_to :user
end

和个人资料标签模型:

class ProfileLabel < ActiveRecord::Base
  belongs_to :company
end

ProfileLabel 有两个属性is_deletedvisible。我怎样才能让ProfileLabelValue 上的has_many 关联只返回那些ProfileLabels is_deleted = falsevisible = true 的值?

如何在我的has_many :profile_label_values 语句中创建一个条件,同时检查ProfileLabel 上的这两个属性?

【问题讨论】:

  • 我们在聊天中解决了您的问题,关于 Rails 3.x 问题。有机会请采纳答案。

标签: ruby-on-rails ruby-on-rails-3 activerecord has-many model-associations


【解决方案1】:

您正在尝试使用连接模型 ProfileLabelValueUserProfileLabel 模型之间创建一个 M-M relationship。为此,我建议您修改模型如下:

class User < ActiveRecord::Base
  ## For Rails 4.x
  ## has_many :profile_label_values, -> { joins(:profile_label).where("profile_labels.is_deleted = ? and profile_labels.visible = ?", false, true ) } 
  ## For Rails 3.x
  has_many :profile_label_values, include: :profile_label, :conditions => "profile_labels.is_deleted = 'f' and profile_labels.visible = 't'"
  has_many :profile_labels, through: :profile_label_values
  belongs_to :company
end

class ProfileLabelValue < ActiveRecord::Base  ## ProfileLabelValue and not profileLabelValue
  belongs_to :profile_label
  belongs_to :user
end

class ProfileLabel < ActiveRecord::Base
  belongs_to :company
  has_many :profile_label_values
  has_many :users, through: :profile_label_values
end

现在,每当您在 User 的实例上调用 profile_label_values 方法时,您都会收到其关联的 profile_label 记录具有 is_deleted = falsevisible = true 的所有 ProfileLabelValue 记录。

例如:

user = User.find(1) ## Get a user record with id 1
user.profile_label_values

【讨论】:

  • 谢谢,但这不是我需要的。我需要获取 profile_label_values,它们的关联 profile_label 没有被删除并且是可见的
  • 请查看我更新的答案。移动了 `has_many :profile_label_values` 的条件。试一试,让我知道。
  • 谢谢,这正是我正在寻找的期望我不能这样做,因为我使用的是 rails 3.0。在 rails 3.0 上是否有类似的功能?
  • 让我们在聊天 chat.stackoverflow.com/rooms/48530/ror 上调试它,因为我没有 Rails 3,但我可以指导你
猜你喜欢
  • 1970-01-01
  • 2011-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 2013-04-22
  • 1970-01-01
  • 2013-12-29
相关资源
最近更新 更多