블로그 인 Rails 4 애플리케이션을 만들고 있는데 사이트에서 게시물 제목을 검색 할 수있는 기능을 원합니다. 나는 결과를 표시하기 위해 게시물의 제목과 show 메소드를 "검색"하기 위해 find 메소드를 사용하고 있습니다. 무슨 일이 있어도, 발견되지 않은 것이 표시됩니다. 당신의 if @title != nil
항상 @title
당신이 그것을 정의되지했듯이 전무 항상 있기 때문에 실패 할 것입니다 때문에 여기 Rails 4로 검색 할 때 문제가 있습니까?
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
검색
<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 %>
귀하의 솔루션은 정확한 일치 항목 만 찾습니다. 만약 당신이 더 많은 히트를 원한다면'Post.where '와 같은 제목을 쓸 수 있습니다.', "% # {@ params [: title]} %"' – froderik