John
John

Reputation: 6612

Selected option not working for select

I have this select which works fine, but default the select is empty and doesn't show the selected value (which is filled correctly):

<%= f.select(:relationgroup, options_for_select(@relationgroups), { :selected => @relation.relationgroup, :include_blank => true}) %>

Any idea why? Thanks!

Upvotes: 5

Views: 2659

Answers (1)

KL-7
KL-7

Reputation: 47608

Try it that way:

<%= f.select(
        :relationgroup, 
        options_for_select(@relationgroups, @relation.relationgroup), 
        :include_blank => true
) %>

Not sure, but maybe it'll work better.

Anyway, assuming Relationgroup is some model with id and name (or any other attribute that you want to be visible in select options) attributes, and you're using default relationgroup_id foreign key in your model you'd better construct your select like that:

<% f.select(
       :relationgroup_id,
       options_from_collection_for_select(@relationgroups, :id, :name),
       :include_blank => true
) %>

It'll choose selected value based on object.relationgroup_id where object is the model you're building form for. See docs for more information.

Upvotes: 6

Related Questions