user.rb
enum gender_type: [:male, :female]
scope :gender, -> (gender_type) { where gender_type: gender_type}
userscontroller
@users = User.gender(params[:gender_type]).paginate(page: params[:page]) if params[:gender_type].present?
index.html.erb
<%= form_tag users_path, method: :get do %>
<%= select_tag ?????? %>
<%= submit_tag "Search", :name => "nil", :id => "submit-gender" %>
<% end %>
目标是最终:
example.com/users?gender_type=0或example.com/users?gender_type=1
答案 0 :(得分:1)
尝试那种
select_tag 'gender', "<option value=0>male</option><option value=1>female</option>".html_safe
或者像那样
select_tag 'gender', options_for_select([["male",0],["female",1]])
你可以阅读rails api来找到解决方案 http://apidock.com/rails/ActionView/Helpers/FormTagHelper/select_tag
答案 1 :(得分:1)
(我假设您在文件名users.rb
中输入错误并且它是常规的user.rb
模型)
User.gender_types
将返回哈希值{"male" => 0, "female" => 1}
。听起来很简单!
select_tag :gender_type, options_for_select(User.gender_types)
答案 2 :(得分:1)
要从枚举属性中获取映射,您可以use the pluralised version of the the enum attribute name:
User. gender_types
=> { male: 0, female: 1 }
您可以致电Hash.to_a
以获取可以传递给options_for_select
的数组。但您可能希望使用.map
来转换密钥。
class User
self.gender_options
# or use the I18n module to humanize the keys
self.gender_types.map { |k,v| [k.capitalize, v] }
end
end
<%= select_tag 'gender', options_for_select(User.gender_options) %>
答案 3 :(得分:0)
您可以像这样简单地使用
<%= form_for(user) do |form| %>
<%= form.select :gender_types, User.gender_types.keys.to_a %>
<% end %>
但是假设您使用Rails Internationalization I18n(我建议使用),则可能需要在视图帮助器中(或:
# app/helpers/users_helper.rb
def genders_select
User.gender_types.map do |k,v|
[User.human_enum_name(:gender_types, k), v]
end
end
和
<%= form_for(user) do |form| %>
<%= form.select :gender_types, @genders_select %>
<% end %>