我正在从 MetaSearch gem 迁移到 Ransack gem,以便升级到 Rails 3.1,我在搜索多态关联时遇到了问题。现有的MetaSearch语法不能用于Ransack,但我找不到任何提到语法变化的文档。或者Ransack是否支持这个功能。
例如,在MetaSearch的github页面上,给定了以下类。
class Article < ActiveRecord::Base
has_many :comments, :as => :commentable
end
class Post < ActiveRecord::Base
has_many :comments, :as => :commentable
end
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
validates_presence_of :body
end
你可以在你的表单中创建一个像这样的搜索字段(这显然是从Searchlogic中借用的惯例)。
<%= f.text_field :commentable_article_type_body_contains %>
我正在使用这种类型的语法,在MetaSearch中工作得很完美,但是在Ransack中,当查询参数包含这个字段时,我的应用程序就会抛出一个异常。这个异常是。
ActiveRecord::EagerLoadPolymorphicError (Can not eagerly load the polymorphic association :ownable)
有谁知道如何在Ransack中进行这种类型的搜索?
我也在努力解决同样的问题(虽然我的错误是不同的)。我认为你的代码需要。
<%= f.text_field :commentable_of_Article_type_body_contains %>
注意大写的A
这对我很有效。你可以看看Ernie的多态关联测试。此处 (这是页面上最后一个文件)
在我的特殊情况下,即使使用适当的ransack语法,我也继续收到NameError(未初始化的常量)。
# NAME ERROR
<div class="form-group col-xs-12 col-sm-12 col-md-4 col-lg-4">
<%= f.label :identifiable_of_Drug_type_name_or_description_cont %>
<%= f.search_field :identifiable_of_Drug_type_name_or_description_cont, class: 'form-control form-control-bb' %>
</div>
我能够通过使用ransack别名来补救。
class Identifier < ApplicationRecord
# note the missing 'cont' predicate
ransack_alias :name_or_description, :identifiable_of_Drug_type_name_or_description
end
# NO ERROR
<div class="form-group col-xs-12 col-sm-12 col-md-4 col-lg-4">
# 'cont' predicate is declared in the view
<%= f.label :name_or_description_cont %>
<%= f.search_field :name_or_description_cont, class: 'form-control form-control-bb' %>
</div>