Does Ransack support the same polymorhpic belongs_

2019-05-16 13:15发布

问题:

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)