简体   繁体   中英

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. My controller has a before_filter to find all the clients for an instance variable of @clients.

Then I have a form that allows a user to select which client the case_study belongs to.

Using a form_helper, I have the case_studies model scoped to the variable f, and some fields.

<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.

What is the Rails way to do handle this?
Should I use exists? nil? or empty? Should I do this right there in my erb or should I put it in a helper? Should I do something else?


EDIT to show conroller

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] }) %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM