Ruby on Rails:如果有多个,则包括空白

时间:2018-11-19 13:51:46

标签: ruby-on-rails ruby

在表单中,我只想在Client.count>1的情况下包括空白。有干净的方法吗?

现在我正在使用此选择:

= f.select :client_id, Client.all.map{|c| [c.full_name, c.id]}, {include_blank: true}

1 个答案:

答案 0 :(得分:1)

您可以使用小型装饰器:

class ClientDecorator
  def self.form_select_choices
    Client.pluck(:full_name, :id)
  end

  def self.form_select_include_blank?
    { include_blank: Client.count.positive? }
  end
end

因此,在您看来,您可以调用这些类方法:

<%= form.select :client_id, ClientDecorator.form_select_choices, ClientDecorator.form_select_include_blank? %>

现在您可以对其进行测试,并使数据库交互远离视图。