我有一个用户模型:
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_deleted
和visible
。如何在has_many
上设置ProfileLabelValue
关联,仅返回ProfileLabels
is_deleted = false
和visible = true
的<{1}}
如何在我的has_many :profile_label_values
语句中执行条件,同时检查ProfileLabel
上的这两个属性?
答案 0 :(得分:1)
您正尝试使用加入模型M-M relationship
在User
和ProfileLabel
模型之间创建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记录包含ProfileLabelValue
和is_deleted = false
的所有visible = true
条记录
例如:
user = User.find(1) ## Get a user record with id 1
user.profile_label_values