Reputation: 11421
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.
Upvotes: 0
Views: 195
Reputation: 7101
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
Upvotes: 1
Reputation: 2973
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} %>
Upvotes: 1
Reputation: 15089
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)
Upvotes: 1