开发者

Rails/3 - Render partial based on state of instance variable?

开发者 https://www.devze.com 2023-01-05 08:51 出处:网络
Struggling with this one a little bit. I have two parameter search form, when both fields match it returns the row into @person:

Struggling with this one a little bit. I have two parameter search form, when both fields match it returns the row into @person:

So what i want to happen is render one partial before the search, another one if a person is matched and another one if a record is not found.

Where does this logic go and what can I check against?

def index
  if params[:id] && params[:dob]
    @person = Person.where("id = ? and dob = ?", params[:id], para开发者_StackOverflow中文版ms[:dob]).first
  end
end

In my index.html.haml

-if ! @person.nil
  =render :partial => 'found'
-elsif @person.nil
  =render :partial => 'not_found'
-else
  =render :partial => 'welcome'

Problem is that @person.nil? is always true, whether a search is done or not. Anyone have any ideas what to do? What am I missing?


You can simply set the @person nevertheless

def index
  if params[:id] && params[:dob]
    @person = Person.where("id = ? and dob = ?", params[:id], params[:dob])
  else
    @person = false
  end
end

This way you don't have problems with nil and checking if it's nil.

In your view you can just check if @person is false or if size is larger than zero.

-if @person
  -if @person.size > 0
    =render :partial => 'found'
  -else
    =render :partial => 'not_found'
  -end
-else
  =render :partial => 'welcome'
-end
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号