Using the reform gem with Rails, how do I populate a has_many :through nested model

1.4k Views Asked by At

I have a user model and role model, connected in ActiveRecord by:

has_many roles, through: :role_accounts

I want to have an "Edit User" screen that has a list of checkboxes, one for each role. Using the Reform gem (v2.1.0), this a snippet of the form object:

class UserForm < Reform::Form
  property :name
  collection :roles do
    property :id
  end
end

My problem is that when the edit form is submitted, and 2 roles are checked, the params hash looks something like: {"user=>{"name"=>"Joe","roles"=>["2","5",""]}} and I get this error:

[Reform] Your :populator did not return a Reform::Form instance for `roles`.

How do I set up the populator for a has_many through?

Also, I think I first need to delete all the user's roles and then add the roles selected, so they wind up with only the current set of roles. How can I do this with the reform gem?

1

There are 1 best solutions below

0
On

Since Reform does not know what the roles are you have to populate it and so tell it what model a role is. Here is an example from the guides:

collection :songs,
  populator: ->(fragment:, **) {
    # find out if incoming song is already added.
    item = songs.find { |song| song.id == fragment["id"].to_i }

    item ? item : songs.append(Song.new)
  }