Search code examples
ruby-on-railshas-and-belongs-to-manyransack

Ransack's collection_select and HABTM return undefined method


I've been looking over my code over and over again and I can't see my problem.

I have two Models Person and Credential. They have a HABTM relationship.

Person

class Person < ActiveRecord::Base
  attr_accessible :credential_ids 
  has_and_belongs_to_many :credentials

  UNRANSACKABLE_ATTRIBUTES = ["id", "hidden_note", "created_at", "updated_at"]

  def self.ransackable_attributes auth_object = nil
    (column_names - UNRANSACKABLE_ATTRIBUTES) + _ransackers.keys
  end
end

Credential

class Credential < ActiveRecord::Base
  attr_accessible :description, :name
  has_and_belongs_to_many :people

  UNRANSACKABLE_ATTRIBUTES = ["id", "created_at", "updated_at"]

  def self.ransackable_attributes auth_object = nil
    (column_names - UNRANSACKABLE_ATTRIBUTES) + _ransackers.keys
  end

end

and here's my form in the People index.html.erb:

<%= search_form_for @search, :class => 'no-bottom-margin form-inline' do |f| %>
    %= f.collection_select(:credentials_id_eq , Credential.all, :id, :name )%>
    <div class='actions'><%= f.submit "Search", :class => 'btn btn-primary btn-large' %></div>
<% end %>

And lastly, this is the error I'm getting.

undefined method `credentials_id_eq' for #<Ransack::Search:0x00000105aa4f28>

Solution

  • So if you make a Model's attribute UNRACKSACKABLE like so:

    UNRANSACKABLE_ATTRIBUTES = ["id", "created_at", "updated_at"]
    

    You can't use Ransack's :model_attribute_predicate function with that particular attribute. Like so, :credentials_id_eq

    It's pretty obvious now, but I wanted to to hide id from the user when making a custom query, but make it available to myself. I changed the ransack function :credentials_name_cont and it worked just fine. Also, removing id from the list of unracksackable attributes will work.