Rails 4:将复选框结果保存到序列化阵列

时间:2015-06-12 23:36:19

标签: ruby-on-rails ruby ruby-on-rails-4 checkbox form-helpers

我的Campaign模型带有channel列。此channel将通过复选框存储serialized个选定结果数组。

这是模特..

应用/模型/ campaign.rb

class Campaign < ActiveRecord::Base
    serialize :channels, Array
end

应用/控制器/ 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

带有复选框的表单部分..

视图/活动/ _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 %>

我在Campaign对象中保存这些结果时遇到问题。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:22)

首先,您提到列名称为channel,但您在Campaign模型中使用了其复数版本。由于您计划在此列中保存通道数组,因此我建议您将数据库中列的名称更改为channels。下面的所有代码都假定您将数据库列更改为channels

由于您要将channels属性序列化为Array,并且您的表单会将该参数作为数组发送到控制器,因此您需要相应地更新campaign_params方法。 / p>

def campaign_params
  params.require(:campaign).permit(:name, :comment, :plan_id, :program_id, :campaign_id, uploadpdf_ids: [], channels: [])
end

现在,@campaign表单的相关部分应如下所示:

<ul class="channels-list">
  <% ["Folder", "Fax", "Email"].each do |channel| %>
    <li><%= check_box_tag "campaign[channels][]", channel, @campaign.channels.include?(channel), id: "campaign_channels_#{channel}" %> <%= channel %></li>
  <% end %>
</ul>

<强>解释

check_box_tag中的第一个参数是标记的name属性。其次是value属性。第三个是布尔值,用于判断最初渲染时是否检查复选框。这将有助于edit表单显示当前选择。

请注意,我明确提供了id属性。如果我们不这样做,那么所有三个复选框都将具有相同的id(从其名称派生),这不是有效的HTML,因为id不应该重复。

生成的HTML应如下所示:

<li><input type="checkbox" name="campaign[channels][]" id="campaign_channels_Folder" value="Folder" /> Folder</li>
<li><input type="checkbox" name="campaign[channels][]" id="campaign_channels_Fax" value="Fax" /> Fax</li>
<li><input type="checkbox" name="campaign[channels][]" id="campaign_channels_Email" value="Email" /> Email</li>

controller会将channels参数视为选定值数组。

这适用于New和Edit表单。