将改革 gem 与 Rails 一起使用,如何填充 has_many :through 嵌套模型



我有一个用户模型和角色模型,在ActiveRecord中通过以下方式连接:

has_many roles, through: :role_accounts

我想要一个"编辑用户"屏幕,其中包含一个复选框列表,每个角色一个复选框。使用改革 gem (v2.1.0),这是表单对象的片段:

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

我的问题是,当提交编辑表单并检查 2 个角色时,params 哈希看起来像这样: {"user=>{"name"=>"Joe","roles"=>["2","5",""]}} 我收到此错误:

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

如何设置has_many的填充器?

另外,我认为我首先需要删除所有用户的角色,然后添加所选角色,因此它们最终只会使用当前的角色集。我怎样才能用改革宝石做到这一点?

由于改革不知道角色是什么,你必须填充它,所以告诉它角色是什么模型。以下是指南中的一个例子:

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)
  }

最新更新