如何为连接两个表的has_many关联写一个条件?

时间:2014-04-29 22:30:10

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

我有一个用户模型:

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。如何在has_many上设置ProfileLabelValue关联,仅返回ProfileLabels is_deleted = falsevisible = true的<{1}}

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

1 个答案:

答案 0 :(得分:1)

您正尝试使用加入模型M-M relationshipUserProfileLabel模型之间创建ProfileLabelValue。为了做到这一点,我建议你修改你的模型如下:

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

现在,只要您在profile_label_values的实例上调用User方法,就会收到其关联的profile_label记录包含ProfileLabelValueis_deleted = false的所有visible = true条记录

例如:

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