【问题标题】:Traversing the models with meta_search and referring to the virtual attributes使用 meta_search 遍历模型并引用虚拟属性
【发布时间】:2011-07-07 13:31:02
【问题描述】:

我正在尝试将 meta_search 应用于一个表单,其中所有属性中的一个是按作者姓名进行的搜索。它在表 authors 中存储为两个属性“first_name”和“last_name”。 我在 Author 模型中创建了以下虚拟属性:

  search_methods :name

  def name 
    self.first_name + " " + self.last_name
  end

我正在搜索的 Authors 和 Books 模型是这样关联的:

class Book < ActiveRecord::Base
  has_many :authors
..

class Author < ActiveRecord::Base
  belongs_to :book
..

现在,当我尝试将以下输入粘贴到视图中时,出现错误:

<%= f.text_field :authors_name_contains, :placeholder => "author.." %>

但如果我通过视图中的“或”运算符将条件应用于属性“first_name”和“last_name”,则它可以工作。

我做错了什么?如何让 meta_search 使用“name”方法?

【问题讨论】:

    标签: ruby-on-rails activerecord meta-search


    【解决方案1】:

    我认为你做不到。如果我理解 meta_search 正确,它会查看 ActiveRecord 生成的属性(或任何你的后端),所以它不会知道你的虚拟属性。

    【讨论】:

    • 据文档中所述,使用范围似乎可以做到这一点:github.com/dogenpunk/meta_search 但是我无法使其工作。这里也建议使用范围(尽管对于搜索逻辑):stackoverflow.com/questions/2801096/…
    • 我目前正在使用这个:` "author.." %> 虽然在视图中看起来很笨重。
    • 也许您需要在模型上创建一个名为 authors_name_contains 的范围?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-30
    • 2016-01-27
    • 1970-01-01
    • 2011-03-11
    相关资源
    最近更新 更多