Does Ransack support the same polymorhpic belongs_to associations in its searches as MetaSearch does?

时间秒杀一切 提交于 2019-12-12 09:52:56

问题


I am migrating from the MetaSearch gem to the Ransack gem for an upgrade to Rails 3.1 and I am having problems with my searches for polymorphic associations. The existing MetaSearch syntax isn't working for Ransack, but I couldn't find any documentation mentioning any syntax changes. Or whether this feature is supported in Ransack.

For example, from the MetaSearch github page, given the following classes:

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

you can create a search field in your form like this (which is apparently a convention borrowed from Searchlogic):

<%= f.text_field :commentable_article_type_body_contains %>

I am using this type of syntax, which works perfectly in MetaSearch, but with Ransack my application is throwing an exception when the query parameter contains this field. The exception is:

ActiveRecord::EagerLoadPolymorphicError (Can not eagerly load the polymorphic association :ownable)

Does anyone know how to do this type of search in Ransack?


回答1:


I was struggling with the same problem (although my error was different). I think your code needs to be:

<%= f.text_field :commentable_of_Article_type_body_contains %>

note the capital A

That worked for me. You can checkout Ernie's tests for polymorphic associations here (it's the last file on the page)



来源:https://stackoverflow.com/questions/13077954/does-ransack-support-the-same-polymorhpic-belongs-to-associations-in-its-searche

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!