Skip to content

How to: custom logic for updating & initialising an instance

johansenja edited this page Nov 3, 2020 · 1 revision

There exists a method #update_instance, which takes a block which is given two arguments: the instance to be updated, and the attributes to be assigned. Default behaviour would be for the instance to be updated with all of the attributes as they are, but attributes can be modified or a custom behaviour set.

Consider this example (taken from https://github.com/TrestleAdmin/trestle/issues/328), where a multiselect form item passes through an additional blank value, which is to be removed from the array:

Trestle.resource(:items) do
  #
  # ...
  #
  update_instance do |instance, attrs|
    attrs[:property] = Array(attrs[:property]).reject(&:blank?)
    instance.assign_attributes(attrs)
  end
end

Similarly, there exists a #build_instance method, which also takes a block, which is given two arguments: attrs and params. attrs are the set of attributes to be assigned, and params are the params from the new page. This sets how an instance should be built when creating a new record.

For example:

You could link to a new item, passing some params in the url:

admin_link_to(
  "New Item",
  admin: ItemsAdmin,
  action: :new,
  params: { user_id: user.id },
  class: "btn btn-success",
)

Those params are available in build_instance, and can be assigned to the new instance:

  build_instance do |attrs, params|
    if params[:user_id].present?
      attrs[:user_id] = params[:user_id]
    end
    self.model.new(attrs)
  end