class Subject
has_many :subject_attribute_types
has_many :subject_attributes
accepts_nested_attributes_for :subject_attributes
end
class SubjectAttributeType
belongs_to :subject
has_many :subject_attributes
attr_accessible :type_name
end
class SubjectAttribute
belongs_to :subject
belongs_to :subject_attribute_type
attr_accessible :value
end
例如:
s1 = Subject.create()
s2 = Subject.create()
sat1 = SubjectAttributeType.create(subject: s1, name: 'Age')
sat2 = SubjectAttributeType.create(subject: s1, name: 'Sex')
sat3 = SubjectAttributeType.create(subject: s2, type_name: 'Age')
sat5 = SubjectAttributeType.create(subject: s2, type_name: 'Username')
SubjectAttribute.create(subject: s1, subject_attribute_type: sat1, value: 20)
SubjectAttribute.create(subject: s1, subject_attribute_type: sat2, value: "male")
SubjectAttribute.create(subject: s2, subject_attribute_type: sat3, value: 21)
SubjectAttribute.create(subject: s2, subject_attribute_type: sat1, value: "user1")
问题:
搜索确切的subject_attributes的最佳做法是什么
如果我想查找年龄> gt = = 18且昵称如%user%
目前我正在使用ransack gem,但我无法想出如何在nested_attributes上进行搜索
答案 0 :(得分:0)
我发现您的应用的商业逻辑存在问题。你为什么需要你的AttributeType来了解任何一个主题?
class Subject < ActiveRecord::Base
has_many :subject_attributes
has_many :attribute_types, through: :subject_attributes
end
class SubjectAttribute < ActiveRecord::Base
belongs_to :attribute_type
belongs_to :subject
attr_accessible :attribute_type_id, :subject_id, :value
end
class AttributeType < ActiveRecord::Base
attr_accessible :type_name
end
之后如果插入一些数据:
s1 = Subject.create
s2 = Subject.create
sat1 = AttributeType.create(type_name: "Age")
sat2 = AttributeType.create(type_name: "Sex")
sat3 = AttributeType.create(type_name: "Username")
SubjectAttribute.create(subject:s1, attribute_type:sat1, value: 20)
SubjectAttribute.create(subject:s1, attribute_type:sat2, value:"male")
SubjectAttribute.create(subject:s2, attribute_type:sat1, value:21)
SubjectAttribute.create(subject:s2, attribute_type:sat3, value:"user1")
你将能够做出选择。 在您的示例中,您使用了多个属性,因此您必须提出多个请求:
通过这种方式,您将找到具有值名称的主题:
names = Subject.joins(:attribute_types).where("attribute_types.type_name = 'Username'
and value like '%user%'")
=> [#<Subject id: 2, created_at: "2013-05-29 11:11:51", updated_at: "2013-05-29 11:11:51">]
通过这种方式,您可以找到具有价值年龄的主题
ages = Subject.joins(:attribute_types).where("attribute_types.type_name = 'Age'
and value >= 18")
=> [#<Subject id: 1, created_at: "2013-05-29 11:11:42", updated_at: "2013-05-29 11:11:42">,
#<Subject id: 2, created_at: "2013-05-29 11:11:51", updated_at: "2013-05-29 11:11:51">]
这样你就可以找到交叉的主题
subjects = (names&ages)
=> [#<Subject id: 2, created_at: "2013-05-29 11:11:51", updated_at: "2013-05-29 11:11:51">]
使用动态attribute_types使选择非常困难。因此,如果您可以为每个类型值参数单独请求,请使用它。否则它可能只是主题列?