2013-12-15 2 views
1

블로그 인 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 %> 
+0

귀하의 솔루션은 정확한 일치 항목 만 찾습니다. 만약 당신이 더 많은 히트를 원한다면'Post.where '와 같은 제목을 쓸 수 있습니다.', "% # {@ params [: title]} %"' – froderik

답변

1

에 대한 HTML이다 "Not found"가 표시됩니다.

당신은 할 필요가 :

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 

는 또한 같은 find_by_title는 레일 4에서 사용되지 않습니다 그 동적 파인더에주의 당신은 where로 교체해야합니다. 당신이 저를 허용하는 경우 @post = Post.find_by_title(@params[:title])에 대한 예를 들어, 당신은, 단지 호기심에서, 또한 @post = Post.where(title: @params[:title])

0

써서 : 당신의 show 방법에, 당신은 PARAMS의 ID를 갖고있는 것 같다. @post = Post.find(params[:title][:id])을 사용하여 객체를 ID로 검색하면 어떨까요? unrequested tip = 죄송합니다.

관련 문제