![](/img/trans.png)
[英]How do I use an instance variable assigned in a helper_method from a helper?
[英]What do I do about an empty instance variable in a form helper?
我有两个关联的模型,其中case_studies属于客户,而客户has_many很多案例研究。 我的控制器有一个before_filter来查找@clients实例变量的所有客户端。
然后,我有一个表格,允许用户选择case_study属于哪个客户端。
使用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>
这一切都很好, 除非数据库中没有客户端。 我知道这是因为@clients为nil,并且它正在尝试对nil做一个collect方法,该方法会崩溃。
Rails处理此问题的方法是什么?
我应该使用存在吗? 零? 还是空的? 我应该在我的erb中执行此操作还是应该将其放入助手中? 我还应该做点别的吗?
我的控制器非常简单。 它有一些来自炼厂的神秘的黑魔法,我刚刚添加了一个前置过滤器
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
也许这是一种可怕的气味? 不笑就太容易了。 对我的卫生的任何建议也表示赞赏
我认为这样做很容易:
<%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.