问题
I am using Rails 4.2.5, Ruby 2.2, ransack. I am trying to implement search functionality using Ransack. I have something like:
These code are in abc_controller.rb:
def checked_users
emails = ["abc@abc.com", "a@a.com", "b@b.com"]
users_list = User.where("email in (?)", emails)
@q = users_list.ransack params[:q]
end
These are the code in checked_users.html.haml: (Ignore the url path here. Its correct, for now I have changed it)
= search_form_for @q, url: checked_users_path(some_id: id) do |form|
= form.text_field :user_name_or_user_email_cont, placeholder: 'Name or email', class: 'form-control'
In routes.rb:
resources :xyz do
resources :mno do
get 'checked_users', controller: 'abc', action: 'checked_users'
end
end
With these code I am getting an error:
ActionView::Template::Error (undefined method `user_name_or_user_email_cont' for Ransack::Search<class: User, base: Grouping <combinator: and>>:Ransack::Search):
Not sure why I am getting this error.
回答1:
Since you're searching for users, I think you can get rid of the user prefix on the text field.
For example, you have:
form.text_field :user_name_or_user_email_cont, placeholder: 'Name or email', class: 'form-control'
Changing it to something like this should work:
form.text_field :name_or_email_cont, placeholder: 'Name or email', class: 'form-control'
Also, I would consider using ransack's search_field instead of text_field if you can.
Here's some additional information. I believe you only need to use a prefix like user if you want to search associations. For example, let's say you have a user and toy model like this:
class User
# attribute: first_name, String
# attribute: last_name, String
has_many :toys
end
class Toy
# attribute: name, String
end
Now, you can perform a ransack search on the user or the user's toys. Here's how you'd use search_field to do this. In this case, first_name and last_name refer to the user, and toys_name refers to a toy's name.
form.search_field :first_name_or_last_name_or_toys_name_cont, placeholder: "First Name, Last Name, or Toy's Name", class: 'form-control'
来源:https://stackoverflow.com/questions/48274694/ransack-search-error