Understanding Rails: index action- how to return none when no search param present?
I have a very basic index action that accepts a search param. And it works...
def index
if params[:search]
@reports = Report.where("title LIKE ?", "%#{params[:search]}%")
else
@reports = Report.all
end
end
But, it shows ALL records when there is no se开发者_运维技巧arch parameter...where i'd like it to show none. Tried setting @reports = nil
but that threw an error.
What's the proper way to do this?
Update: adding error message per request:
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.each
Extracted source (around line #16):
13: <th>File Type</th>
14: <th>Title</th>
15: </tr>
16: <% for report in @reports %>
17: <tr>
18: <td><%= report.serial %></td>
19: <td><%= report.file_kind %></td>
If you want @reports
to be an array you could do :
@reports = params[:search].present?? Report.where("title LIKE ?", "%#{params[:search]}%").all : []
If you want to be uber-clever but not super db efficient this gives you @reports
as an ActiveRelation
@reports = Report.where(params[:search].present?? ["title like ?", "%#{params[:search]}%"] : "id < 0")
But really, the controller isn't the offending portion here. When @reports
is nil
where does the error come from? Most likely you should do
def index
@reports = Report.where("title LIKE ?", "%#{params[:search]}%") if params[:search].present?
end
and then make sure the rest of your action can handle a nil @reports
gracefully.
There is nothing wrong with setting the @reports variable to nil. I suspect that the error is thrown from either an after filter or the view itself, where you probably have some code that doesn't expect @reports to be nil. What error are you getting?
Jesse suggestion is correct. But, it still shows the error on your view page. So, you just add the if condition at the end for end section.
... <% end if @reports != nil %>
精彩评论