I have a Campaign model with a channel column. This channel will store a serialized array of chosen results via checkboxes.
Here's the model..
app/models/campaign.rb
class Campaign < ActiveRecord::Base
serialize :channels, Array
end
app/controllers/compaigns_controller.rb
class CampaignsController < ApplicationController
def index
@campaigns = Campaign.all.order("created_at DESC")
end
def new
@campaign = Campaign.new
end
def create
@campaign = Campaign.new(campaign_params)
if @campaign.save
zip = Uploadzip.find(params[:uploadzip_id])
zip.campaign = @campaign
zip.save
flash[:success] = "Campaign Successfully Launched!"
redirect_to @campaign
else
flash[:error] = "There was a problem launching your Campaign."
redirect_to new_campaign_path
end
end
def show
@campaign = Campaign.includes(:program, :uploadzip, :channel, :plan, :uploadpdfs).find(params[:id])
end
private
def campaign_params
params.require(:campaign).permit(:name, :comment, :channel, :plan_id, :program_id, :campaign_id, uploadpdf_ids: [])
end
end
The part of the form with checkboxes..
views/campaigns/_target.rb
<%= form_for @campaign, url: {action: "create"} do |f| %>
...
<label class="right-inline">
<%= f.label :channel, "Distribution Channel", class: "right-label" %>
</label>
<ul class="channel-list">
<% ["Folder", "Fax", "Email"].each do |channel| %>
<li><%= check_box_tag :channel, channel %> <%= channel %>
<% end %></li>
</ul>
...
<% end %>
I'm having problems saving these results inside the Campaign object.
Any help is highly appreciated.
First of all, you mentioned that the column name is
channel, but you have used its plural version inCampaignmodel. Since you are planning to save array of channels in this column, I would suggest you change the name of the column in the database tochannels. All the code below assumes that you will change the database column tochannels.Since you are serializing the
channelsattribute to anArrayand your form will send that parameter as an array to the controller, you will need to update yourcampaign_paramsmethod accordingly.Now, the relevant part of your
@campaignform should look like this:Explanation
First argument in
check_box_tagisnameattribute of the tag. Second isvalueattribute. Third is boolean value to tell whether the checkbox will be checked or not when rendered initially. This will be helpful ineditform to show current selections.Note that I am providing
idattribute explicitly. If we don't do that, all three checkboxes will have the same id (derived from their names), which would not be valid HTML because id should not be repeated.Generated HTML should look like this:
The
controllerwill seechannelsparam as an array of selected values.This should work both for New and Edit forms.