[英]What do I do about an empty instance variable in a form helper?
I have two associated models where case_studies belong_to clients and clients has_many case studies. 我有两个关联的模型,其中case_studies属于客户,而客户has_many很多案例研究。 My controller has a before_filter to find all the clients for an instance variable of @clients. 我的控制器有一个before_filter来查找@clients实例变量的所有客户端。
Then I have a form that allows a user to select which client the case_study belongs to. 然后,我有一个表格,允许用户选择case_study属于哪个客户端。
Using a form_helper, I have the case_studies model scoped to the variable f, and some fields. 使用form_helper,我将case_studies模型的作用域限定为变量f和一些字段。
<div class='fields'>
<%= f.label :case_study_title -%>
<%= f.text_field :case_study_title -%>
<%= f.label :which_client_does_this_belong_to? -%>
<%= f.select(:client_id, @clients.collect{ |c| [c.name, c.id] }) -%>
</div>
This all work great except when there are no clients in my database. 这一切都很好, 除非数据库中没有客户端。 I know it's because @clients is nil, and it's trying to do a collect method on nil, which will blow up. 我知道这是因为@clients为nil,并且它正在尝试对nil做一个collect方法,该方法会崩溃。
What is the Rails way to do handle this? Rails处理此问题的方法是什么?
Should I use exists? 我应该使用存在吗? nil? 零? or empty? 还是空的? Should I do this right there in my erb or should I put it in a helper? 我应该在我的erb中执行此操作还是应该将其放入助手中? Should I do something else? 我还应该做点别的吗?
my controller is very simple. 我的控制器非常简单。 it has some mysterious crudify black magic from the refinerycms and I just added a before filter 它有一些来自炼厂的神秘的黑魔法,我刚刚添加了一个前置过滤器
module Refinery
module CaseStudies
module Admin
class CaseStudiesController < ::Refinery::AdminController
before_filter :find_all_clients
crudify :'refinery/case_studies/case_study', :xhr_paging => true
protected
def find_all_clients
@clients = Refinery::Clients::Client.all
end
end
end
end
end
perhaps this is a terrible smell? 也许这是一种可怕的气味? it's too easy not to be lol. 不笑就太容易了。 any advice on my hygiene is appreciated also 对我的卫生的任何建议也表示赞赏
I think it's easy enough to just do: 我认为这样做很容易:
<%unless @clients.empty?%>
<%= f.label :which_client_does_this_belong_to? %>
<%= f.select(:client_id, @clients.collect{ |c| [c.name, c.id] }) %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.