Question

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?

Was it helpful?

Solution

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)

OTHER TIPS

In my particular case, I continued to receive a NameError (uninitialized constant) even when using the appropriate ransack syntax.

View

# 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>

I was able to remedy this by using a ransack alias:

Model

class Identifier < ApplicationRecord
  # note the missing 'cont' predicate
  ransack_alias :name_or_description, :identifiable_of_Drug_type_name_or_description
end

View

# 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>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top