Topic: 'selected' if p.id == @object.some_id

I hope the subject is understandable..

I have this in a partial:

<select name="kalender[plats_id]" id="kalender_plats_id">
    <% for p in @platser %>
        <option value="<%= p.id %>"
        <%= ' selected' if p.id == @kalender.plats_id %>><%= p.name %></option>
    <% end %>
</select>

And it doesn't work, i.e the <option> isn't selected when the id's match.

I've tried sending it with

render :partial, :object => @kalender

but that doesn't do any good either.

Last edited by Hans Nilsson (2007-02-02 14:16:07)

Re: 'selected' if p.id == @object.some_id

Try collection_select. It's much shorter and easier:

<%= collection_select :kalender, :plats_id, @platser, :id, :name %>

Is that selecting the proper value?

Railscasts - Free Ruby on Rails Screencasts

Re: 'selected' if p.id == @object.some_id

Wow, that is really short and sweet, but doesn't select any value...

Re: 'selected' if p.id == @object.some_id

Are both the "id" and "plats_id" columns in the database of type "integer"? Are you certain the kalender record you are editing has a value in the plats_id column?

Railscasts - Free Ruby on Rails Screencasts

Re: 'selected' if p.id == @object.some_id

Yes, both are integers, kalender always has a plats_id. When I print out @kalender.plats_id as it is, outside the loop, it prints it right.

Re: 'selected' if p.id == @object.some_id

Not sure what the problem is. You can try launching script/console and comparing the values to see what is wrong:

# in script/console
kalender = Kalender.find(:first) # or preferably the record you are using when testing the interface
plats = kalender.plats
kalender.plats_id == plats.id # see what this returns
kalender.plats_id.class # and this
plats.id.class # and this

Railscasts - Free Ruby on Rails Screencasts

Re: 'selected' if p.id == @object.some_id

I know the problem. You are missing a ">" after the first option statement.

Re: 'selected' if p.id == @object.some_id

He's not missing a '>'. The closing '>' is on the 4th line.

I had this problem before. Try p == @kalender.plats