Rails/3 - 根据实例变量的状态渲染部分?

发布于 2024-09-07 23:30:33 字数 565 浏览 1 评论 0原文

在这个问题上有点挣扎。我有两个参数搜索表单,当两个字段匹配时,它将行返回到 @person:

所以我想要发生的是在搜索之前渲染一个部分,如果匹配了一个人则渲染另一个部分,如果找不到记录则渲染另一个部分。

这个逻辑在哪里?我可以检查什么?

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

在我的index.html.haml

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

问题是@person.nil?无论是否进行搜索,始终为真。有人知道该怎么做吗?我缺少什么?

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], params[: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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

迷荒 2024-09-14 23:30:33

不过你可以简单地设置 @person

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

这样你就不会遇到 nil 和检查它是否为 nil 的问题。

在您看来,您只需检查 @person 是否为 false 或者 size 是否大于零。

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文