I have two models connected by a join table: Users and Agencies (joined by AgencyUserRelationships). A user has many relationships, each relationship having one agency, but they do not necessarily have relationships to all Agencies.

I want to create a Simpleform for a user which displays all the agencies as a list of checkboxes, where the existing relationships are already checked. Submitting the form updates/deletes existing relationships if they are unchecked and creates new ones if they get checked. This sounded like a job for accepts_nested_attributes_for but my attempts are failing (see below)

User.rb

has_many :agency_user_relationships
accepts_nested_attributes_for: agency_user_relationships

AgencyUserRelationship.rb

belongs_to :user
belongs_to :agency

Simple Form Code

= simple_form_for user do |f|
  = f.input :agency_user_relationships, collection: Agency.all, as: :check_boxes, label: t(:agencies)
  = button_tag type: :submit, "Add"

This ends up giving me a form that has one row for each Agency (which is what I want), but the existing relationships aren't checked.

I looked at Simpleforms docs, but following the example there just gives me a form with two rows for editing the nested resource, which isn't really what I want, I don't think.

有帮助吗?

解决方案

It turned out I was pretty close. I changed f.input to f.association and Rails knew what to do.

It turned my simpleform code into

= simple_form_for user do |f|
  = f.association :agency_user_relationships, as: :check_boxes, collection: Agency.all, label: t(:agencies)
  = button_tag type: :submit, class: 'btn btn-primary controls' do
    = t(:add_agency)

Now, the form shows up with all the Agencies that exist, but the ones which already have relationships with my user are checked by default. The rest is controller code.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top