user3103753
user3103753

Reputation: 11

Issue with search with Rails 4?

I am making a Rails 4 application that is a blog and I would like to have the ability on the site to search the titles of the posts. I am using the find method to "search" the titles of the posts and the show method to display the result. No matter what, not found is displayed.

def find
  @params = params[:post]
  title = @params[:title]
  @post = Post.find_by_title(@params[:title])
  respond_to do |format|
  if @title != nil
    format.html {render :action => :show}
  else
    format.html { render :action => :not_found }  
  end
end
end



def show
id = params[:item][:id]
    @post = Post.find_by_title(@params[:title])


respond_to do |format|
  if @post != nil
    format.html
  else
    format.html{render :action => "not_found"}
  end
end
end

Here is the HTML for the search

<h2>Find a post</h2>
<h3><%= form_for  :post, :url => {:action => :find} do |form| %>
<p><label for="title">Name:</label>
<%= form.text_field  :title, :size => 20 %></p>
<p><%= submit_tag   "Find a Post" %></p></h3>
<% end %>

Upvotes: 1

Views: 80

Answers (2)

Thyago B. Rodrigues
Thyago B. Rodrigues

Reputation: 630

Also, just out of curiosity, if you allow me: on your show method, you seem to have the ID in the params. Why don't you just retrieve the object by it's ID, using @post = Post.find(params[:title][:id])? Sorry for the unrequested tip =]

Upvotes: 0

vee
vee

Reputation: 38645

"Not found" is displayed because your if @title != nil is always going to fail because @title is always nil as you've not defined it.

You need to do:

def find
  @params = params[:post]
  @title = @params[:title]  # <--------- here set `title` to `@title`
  @post = Post.find_by_title(@params[:title])
  respond_to do |format|
  if @title != nil
    format.html {render :action => :show}
  else
    format.html { render :action => :not_found }  
  end
end
end

Also note that dynamic finders such as find_by_title are deprecated in Rails 4. You should replace them with where. For example for @post = Post.find_by_title(@params[:title]) you'd write @post = Post.where(title: @params[:title])

Upvotes: 1

Related Questions