質問

I have a Rails 4 application. I have a search function with a select field. Now I'm getting this error:

NoMethodeError: undefined method 'map' for "5":String: select * from users inner join user_texts on users.id = user_id where text_id = ?

Here's view:

<% form_tag user_path do
 <% select_tag :text_id, Option_from_collection_for_select(text.all, :id, :name, params[:text_id]), include_blank: true %>
<%= button_to '#', class: 'btn btn-default' do %>
<% t(:find) %>
<% end %>

Here's controller:

def index
  if params[:text_id].present?
     @users = User.search params[:text_id]
  end
  @users = User.all
end

Here's model:

def self.search(text_id)
find_by_sql("select * from users inner join user_texts on users.id = user_id where text_id = ?
", text_id)
end

When I do this, it works perfect:

select * from users inner join user_texts on users.id = user_id where text_id = 5
役に立ちましたか?

解決

Change your method to this

def self.search(text_id)
  User.joins(:user_texts).where("text_id = ?", text_id)
end

Two reasons why you should change

  1. This is more rails-y way of doing it
  2. find_by_sql doesn't work well with query placeholders

他のヒント

The above answer is perfectly fine and recommended, but sometimes you have to fetch from a raw sql query. And the error above is we need to use square brackets [ instead of round ( ones. Check out the API

So this should have worked.

def self.search(text_id)
   find_by_sql ["select * from users inner join user_texts on users.id = user_id where text_id = ?
   ", text_id ]
end
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top