Felix Felix - 11 months ago 37
Ruby Question

Rails setting selection tag to predifined value

I have a add function + view. In some cases a user can specify to do some action and call a function that should submit a id to the add function. (that works)

Now I wanted that if this param is not nil then a selection tag should be predifined with this value.

I tried this:

<% if !params[:channel_id].nil? %>
<% :channel_id << params[:channel_id] %>
<% end %>

Thats not working.

selection tag looks like this:

<%= f.collection_select :channel_id, @channels, :id, :channelname, {prompt: (t "channel.add.prompt")}, class: "form-control", :required => :true %>

is there a solution to achieve this?


You could just add the value to your collection_select:

<%= f.collection_select :channel_id, @channels, :id, :channelname, 
        prompt: t('channel.add.prompt'),
        selected: params[:channel_id]
      class: 'form-control', required: true %>

Another option - which I would prefer - is to set this value when you initialize the object for the form. This depends on how your form_for looks like, but it might look like this:

# in the controller
@model = Model.new(channel_id: params[:channel_id])

# in the view
<%= form_for @model do |f| %>

If it is done this way, then there is no need to change the collection_select tag.