ruby on rails:如果不止一个,则包含空白



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

现在我使用这个选择:

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

您可以使用一个小型装饰器:

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? %>

现在您可以测试这一点,并将数据库交互远离视图。

最新更新