Ruby on rails 对“新建”和“编辑入轨”使用“选择入轨”窗体

Ruby on rails 对“新建”和“编辑入轨”使用“选择入轨”窗体,ruby-on-rails,ruby-on-rails-4.1,Ruby On Rails,Ruby On Rails 4.1,在my helpers/roles_helper.rb中,我有: Rails 4.1 Ruby 2.1.1 def角色列表\u生成器 角色=角色.all.order(:角色) 如果角色 角色矩阵=['',]] 角色。每个do | r| 角色矩阵 但这并不奏效 解决方案: 这是将在form.html.erb中显示的内容: def roles_list_generator roles = Role.all.order(:role) if roles roles_matrix =

在my helpers/roles_helper.rb中,我有:

Rails 4.1
Ruby 2.1.1
def角色列表\u生成器
角色=角色.all.order(:角色)
如果角色
角色矩阵=['',]]
角色。每个do | r|
角色矩阵
但这并不奏效

解决方案: 这是将在form.html.erb中显示的内容:

def roles_list_generator
  roles = Role.all.order(:role)
  if roles
    roles_matrix = [['','']]
    roles.each do |r|
      roles_matrix << [r.description,r.role]
    end
    return roles_matrix
  end
end
    <%= f.select :role, options_for_select(roles_list_generator) %> 
<%= f.select :role, options_for_select(roles_list_generator), :selected => @user.role %>

有什么想法吗

试试看

<%= f.select :role, options_for_select(roles_list_generator, @user.role) %>
然后,您可以尝试使用自定义方法-添加提示:true。这将消除填充空条目的需要

f.collection_select :role, Role.all.order(:role), :id, :description
以下是文件:

是否支持改为[r.description,r.id]呢?如果我想要的值是r.role,为什么会是r.id呢?有人投票结束了这个问题?我希望巨魔们能说出他们投票的原因。对不起,我猜这是一个令人困惑的角色。最好的方法是使用id、name作为属性,以便可以调用Role.first.name。这就是为什么我要说:id。我不确定我是否了解它的优点。我的表有一个ID字段、一个角色和一个描述。对于此特定表单,我希望选择角色并显示描述。然而,这与我提出的问题无关。
f.collection_select :role, Role.all.order(:role), :id, :description
f.collection_select :role, Role.all.order(:role), :id, :description, prompt: true