Craig
Craig

Reputation: 159

Rails form multiple checkboxes for associated model

I'm creating an application where a "submission" can be made using a form which creates client details and allows "referrals" to be created depending on the branch(es) that can provide the required service

class Submission < ActiveRecord::Base
  has_many :referrals, :inverse_of => :submission, dependent: :delete_all
  accepts_nested_attributes_for :referrals, :allow_destroy => true
end

class Referral < ActiveRecord::Base
  belongs_to :submission
end

class Branch < ActiveRecord::Base
  has_many :referrals
end

Submissions controller:

def new
  @submission = Submission.new
  @submission.build_client
  @submission.client.build_address
  @submission.referrals.build
end

def submission_params
  params.require(:submission).permit(:consent, :user_id, client_attributes:
    [:client_id, :first_name,
      address_attributes:
        [:first_line, :second_line,]
    ],
    referrals_attributes:
      [:branch_id]
  )
end

The Submission form:

<%= form_for(@submission) do |f| %>
  <%= f.fields_for :referrals do |referral| %>
    <%= render 'referral_fields', f: referral %>
  <% end %>
<% end %>

_referral_fields.html.erb:

    <% Branch.all.where(referrable: true).each do |branch| %>
       <label>
          <%= check_box_tag 'branch_ids[]', branch.id %>
          <%= branch.name %>
       </label>
    <% end %>

What I want is to have checkboxes for each referrable branch. When a branch is ticked and the submission is created, a referral will be created for that branch. However, when I submit the form, I get a validation error of "Referrals can't be blank". Any idea why this is not working?

Any help is most appreciated

Upvotes: 0

Views: 604

Answers (1)

max
max

Reputation: 101811

Use collection_check_boxes.

<% # _referral_fields.html.erb %>
<%= f.collection_check_boxes(:branch_ids, Branch.where(referrable: true), :id, :name) do |b|
  b.label { b.check_box } # wraps check box in label
end %>

You would need to whitelist submission[referrals_attributes][branch_ids] - not branch_id.

def submission_params
  params.require(:submission)
    .permit(
      :consent, 
      :user_id, 
      client_attributes: [
        :client_id, 
        :first_name,
        address_attributes: [
          :first_line, :second_line,
        ]
    ],
    referrals_attributes: [:branch_ids]
  )
end

Edited.

However for this to work you need to setup a relation between Referral and Branch. In this case you could use either a has_and_belongs_to_many (HABTM) or has_many though: (HMT) relationship.

See Choosing Between has_many :through and has_and_belongs_to_many.

class Referral < ActiveRecord::Base
  belongs_to :submission
  has_and_belongs_to_many :branches
end

class Branch < ActiveRecord::Base
  has_and_belongs_to_many :referrals
end

You need to create a join table as well:

rails g migration CreateBranchReferralJoinTable branch referral

Upvotes: 3

Related Questions