简体   繁体   中英

need to add default value in f.select field to existing ones - rails 3.2

With the code I have below in the select field I have all the public_campaigns :

<%= f.select :campaign_id, @public_campaigns.map{|x| [x.name,x.id]} %>

public_campaigns is defined in controller with:

@public_campaigns = @logged_in_user.campaigns.order('created_at desc')

In the form I select the campaign and fill up the rest of the form and at the submit action an invitation is created with campaign_id taken from the campaign I selected in the form, it can be anything from 1 to n

What I need now is to have a default item in select field that will have the value of 0 and named "No campaign" , it means I invite someone to a campaign that I have not created yet and in invitation the campaign_id field will be 0 .

Thank you for your time.

Well, the fastest way you can do this is something like this:

@public_campaigns = @logged_in_user.campaigns.order('created_at desc')
no_campaign = Campaign.new(:id => '0', :name => 'No Campaign')
@public_campaigns.unshift(no_campaign)

Do you really need 0? I think use of {:include_blank => "No campaign"} should be enough?

Try this:

<%= f.select :campaign_id, (@public_campaigns.map{|x| [x.name,x.id]} << ["No campaign",0]), {:selected => 0} %>

I'm not sure why you are unable to do it this way:

<%= f.collection_select :campaign_id, @public_campaigns, :id, :name, prompt: 'No campaign' %>

Just check if campaign_id.nil? instead of assigning any value to campaign_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM