如何在超类中创建类似属性的 attr setter 并填充到子类中?
我在 Rails 中有一个继承自 ActiveRecord::Base 的父类。我正在尝试在该类中实现自由文本搜索以及其他查询,以便从它继承的所有类都可以将它与自己的字段一起使用,这些字段根据模型而变化:
#
# in base class
#
class GenericBase < ActiveRecord::Base
named_scope :freetext, lambda { |query|
if query.present?
{ :conditions => [ self.freetext_fields.join(' LIKE ? or '),
( ["%#{query}%"]*self.freetext_fields.size ) ].flatten }
else
{}
end
}
end
#
# in inheriting class
#
class Person < GenericBase
set_freetext_fields %w(firstname lastname username email)
end
# or
class Address < GenericBase
set_freetext_fields %w(street city)
end
#
# in controller
#
def search
@people = Person.freetext(params[:query])
end
在上面的示例中,我如何实现set_freetext_fields
setter 是否可以在从 GenericBase
继承的所有模型中轻松使用?这应该与 Rails 中提供的 set_table_name
非常相似。
我想在父模块或 mixin 模块中实现它,以便继承类的 API 尽可能干净。
I have a parent class in rails that inherits from ActiveRecord::Base. I'm trying to implement a freetext search, plus other queries, in that class such that all classes that inherit from it can use it with their own fields, which change based on the model:
#
# in base class
#
class GenericBase < ActiveRecord::Base
named_scope :freetext, lambda { |query|
if query.present?
{ :conditions => [ self.freetext_fields.join(' LIKE ? or '),
( ["%#{query}%"]*self.freetext_fields.size ) ].flatten }
else
{}
end
}
end
#
# in inheriting class
#
class Person < GenericBase
set_freetext_fields %w(firstname lastname username email)
end
# or
class Address < GenericBase
set_freetext_fields %w(street city)
end
#
# in controller
#
def search
@people = Person.freetext(params[:query])
end
In the example above, how do I implement the set_freetext_fields
setter to be easily used in all models that inherit from GenericBase
? This should be something very similar to set_table_name
available in Rails.
I want to implement it in the parent or a mixin module such that the API for inheriting classes will be as clean as possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以实现如下所示的内容:
其中
C
是GenericBase
类You can implement something like this:
Where
C
isGenericBase
class