0
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 进行搜索的最佳做法是什么。
如果我想查找所有年龄 >= 18 且昵称如 %user% 的主题

目前我正在使用 ransack gem,但我不知道如何在nested_attributes 上进行搜索

4

1 回答 1

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">] 

使用动态属性类型使选择非常困难。因此,如果您可以对每个类型值参数进行单独请求,请使用它。否则也许它真的只是主题列?

于 2013-05-29T12:25:14.093 回答