mass assignment of dependent entity

13 views
Skip to first unread message

cra...@gmail.com

unread,
Aug 3, 2021, 12:39:12 PMAug 3
to sequel-talk
I have a many-to-many relationship between Books and Tags, with an intersection table of books_tags.

I have an HTML form that lists tags as a SELECT (multiple), with a name of 'book[tags]'.

I get an error when trying to update the Book model using mass assignment:

class BookController

    post ':id/edit' do
        # method tags= doesn't exist
        @book = Book[params[:id]].update(params[:book])
    end

end

Do I need to remove the :tags key from the parameter hash, then update the tags dependency separately?

Thanks.

Jeremy Evans

unread,
Aug 3, 2021, 1:46:37 PMAug 3
to seque...@googlegroups.com
You probably want to look into the association_pks plugin, and switch the name of the field to 'book[tag_pks]'.

Note that update(params[:book]) is probably a bad idea, as then you are allowing any fields in the model to be set (other than the restricted fields).  If you are dealing with untrusted input, it's almost always better to use update_fields(params[:book], %w'field1 field2 ...') instead and provide an explicit list of fields to set (matching the fields that are on the related form).

Thanks,
Jeremy

cra...@gmail.com

unread,
Aug 5, 2021, 3:28:24 PMAug 5
to sequel-talk
Thank you.
Reply all
Reply to author
Forward
0 new messages