I'm experiecing some problems with option_from_collection_for_select when the selected value is nil.
I have User model:
class User < ActiveRecord::Base
attr_accessible :email, :password, :password_confirmation, :remember_me, :username, :locale
end
and a Reservation one:
class Reservation < ActiveRecord::Base
belongs_to :user
end
In the reservation add/edit page there is a select with the user is goiing to be associated with the reservation:
<%= select_tag('user_id',
options_from_collection_for_select(@users, :id, :username, @reservation.user.id)) %>
This works in the edit page when @reservation.user.id is not nil but I get the nil error in the add page. Just for now I check if @reservation.user.id is nil and I put the selected value depending if is nil or not; this works but I don't like this solution.
How can I solve this?
There are probably many ways around this:
At the very least, you'd have to put a conditional for the last argument for ofcfs.
options_from_collection_for_select(
@users, :id, :username,
@reservation.user.blank? ? 0 : @reservation.user.id)
Then, in your create action, you'd have to prepend an appropriate hash:
@users = User.all
@users.insert(0, {:id=>0,:username=>'PLEASE SELECT A USER'})
Then you'd have to validate that the value returned from the select isn't 0 before you save a reservation.
There are at least three or four other things I can think of that work around this