Rails Polymorphic association in form via sgid (ActionView & AciveRecord)
how to pass polymorphic association via form securly?
the following is Vanilla Rails feature global_id
the following is Vanilla Rails feature global_id
class TaxReturn belongs_to :author, polymorphic: true def author_sgid author.to_sgid(for: :polymorphic_hidden_field) end def author_sgid=(value) self.author = GlobalID::Locator.locate_signed(value, for: :polymorphic_hidden_field) end end
note: "for:" can be anything, ":polymorphic_hidden_field" is just something I fancy for this situation
# app/controllers/tax_returns_controller.rb def new @tax_return = TaxReturn.new(author: current_user) # current_user == User or Accountant end def create @tax_return = TaxReturn.new(tax_return_params) # .. end def tax_return_params params.require(:tax_return).permit(:author_sgid) end
# app/views/tax_returns/_form.html.erb <%= form_with(model: @tax_return) do |f| %> <%= f.input :author_sgid, as: :hidden %> <% end %>
Inspired by