EastsideDev
EastsideDev

Reputation: 6659

Using a select in form for both new and edit in Rails

Rails 4.1
Ruby 2.1.1

In my helpers/roles_helper.rb, I have:

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

Then, I can use this in my views/users/form.html.erb:

    <%= f.select :role, options_for_select(roles_list_generator) %> 

Which is rendered when I view new: views/users/new.html.erb:

<%= render 'form' %>

The problem is that I can no longer form.html.erb with views/users/edit.html.erb.

I did try:

<%= f.select :role, options_for_select(roles_list_generator), :selected => @user.role %>

But that did not work

Solution:

This is what will go int form.html.erb:

<%= f.select :role, options_for_select(roles_list_generator, @user.role) %>

Any ideas?

Upvotes: 0

Views: 58

Answers (1)

Rafal
Rafal

Reputation: 2576

Try

f.collection_select :role, Role.all.order(:role), :id, :description

Then you can try to use your custom method - adding the prompt: true. This will remove the need to populate an empty entry.

f.collection_select :role, Role.all.order(:role), :id, :description, prompt: true

Here are the docs: http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/collection_select

Upvotes: 1

Related Questions