Reputation: 333
I am trying to create a search form for my rails app, the user enters a query and based off that query, I want them to see a list of links associated with that query (these links come from my 'links' table). I created the HTML form and it has the user enter a query. I use this query
<%= form_tag links_path, :method => 'get' do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "search", :name => nil %>
</p>
<% end %>
In my controller for the links table, I have an if
statement that checks what the user has entered and it assigns Link.where('title LIKE ?', '%{#params[:search]}%')
to @links
. and then converts it to an array (.to_a
)
Here is the statement in the index action:
def index
@links = Link.all
if params[:search]
#@links = Link.find(:all, :conditions => ['title LIKE ?', '%{#params[:search]}%'])
@links = Link.where('title LIKE ?', '%{#params[:search]}%')
@links.to_a
end
end
In my index.html.erb
I would like to display the result. I used <%= @links %>
however, it displays the ActiveRecord: #<Link::ActiveRecord_Relation:0x0000000d5c69f0>
How could I convert the query result ActiveRecord into an array, so then I could be able to index it? Thanks.
Upvotes: 0
Views: 1938
Reputation: 1915
Don't EVER EVER EVER EVER use
@links = Link.where('title LIKE ?', '%{#params[:search]}%')
this is a security issue. Check http://railscasts.com/episodes/25-sql-injection.
In order to see all likes as an output just simply do
@links = Link.where('title LIKE ?', params[:search]')
and in Views do
<%= @links.to_a %>
That should help :)
Upvotes: 2
Reputation: 477
You need to assigns @links like this:
@links = @links.to_a
By the way, if you want render link one-by-one using something like @links.each, you do not need to convert @links to array.
Upvotes: 1