【问题标题】:Rails select valuesRails 选择值
【发布时间】:2018-06-16 08:11:04
【问题描述】:

我在表单中有一个选择选项:

<%= f.select :role, options_for_select(User.roles.keys.to_a, params[:role]), {}, class: 'form-control form-control-lg roleSelect' %>

这些角色在我的模型中定义:

enum role: {user: 0, profile_user: 1}

现在,当用户选择它时,我的下拉列表中会显示 userprofile_user 作为下拉选项。

有没有办法在下拉列表中显示另一个值来表示这些值?

例如:

在下拉列表中,我宁愿显示映射到user 的“我是一名教师”。

在下拉列表中,我宁愿显示映射到profile_user 的“我在这里学习”。

【问题讨论】:

标签: ruby-on-rails ruby ruby-on-rails-4


【解决方案1】:

在您的模型中添加您的叙述性描述。

NARRATIVE_ROLES = {user: 'I am a teacher', profile_user: 'I am here to learn'}

添加创建 select_array 的方法

def self.roles_select
  User.roles.keys.map {|role| [NARRATIVE_ROLES[role], role]}
end

然后在你使用的选择中

options_for_select(User.roles_select, params[:role])

或者(稍微简单一点)

NARRATIVE_ROLES = {'I am a teacher' => :user, 'I am here to learn' => :profile_user}

options_for_select(User::NARRATIVE_ROLES, params[:role])

【讨论】:

    猜你喜欢
    • 2014-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-28
    • 1970-01-01
    相关资源
    最近更新 更多