Rails f.select默认选中

时间:2015-11-23 09:06:43

标签: ruby-on-rails

我选择了

<%= f.select :visibility, collection_for_visibility_select, :include_blank => false %>

一个包含select:

值的助手
def collection_for_visibility_select
  [
    [l(:label_crm_contacts_visibility_project), Contact::VISIBILITY_PROJECT],
    [l(:label_crm_contacts_visibility_public), Contact::VISIBILITY_PUBLIC],
    [l(:label_crm_contacts_visibility_private), Contact::VISIBILITY_PRIVATE]
  ]
end

我想在select中添加默认选择值,这就是我尝试过的:

<%= f.select :visibility, collection_for_visibility_select, :selected => Contact::VISIBILITY_PUBLIC, :include_blank => false %>

它为我提供了默认选择值,但是当我想编辑记录并将visibility切换为其他内容时,我仍然有VISIBILITY_PUBLIC

我该如何解决?

1 个答案:

答案 0 :(得分:2)

你可以试试这个:

<%= f.select :visibility, collection_for_visibility_select, :selected => (f.object.visibility.nil? ? Contact::VISIBILITY_PUBLIC : f.object.visibility), :include_blank => false %>

它将首先从模型中读取值,如果为nil,则使用默认值。