Forme with an associated object & nested attributes #123
Replies: 2 comments 2 replies
-
I think the last paragraph in the documentation you quoted is not worded correctly. It should be changed to:
I apologize for the confusion and will push a fix shortly. As the first line in the documentation you quoted states, you cannot use values, validations = obj.forme_parse(hash).values_at(:values, :validations)
obj.set_fields(values, %w'field1 field2 ...')
obj.forme_validations.merge!(validations) |
Beta Was this translation helpful? Give feedback.
-
The documentation is a bit sparse about this topic. I found that even your previous example didn't work, as I believe I should rather use the Roda "frome_set" plugin version of So the following code works for updating the direct name attribute & allow to set (or unset) the associated Artist object. class Album < Sequel::Model
many_to_one :artist
plugin :forme
plugin :forme_set
plugin :nested_attributes
nested_attributes :artist
def validate
super
errors.add(:name, "validation should always add an error")
end
end r.post do
@album = Album[r.params["id"]]
# Parse _forme_set_data from r.params, verify csrf & hmac then return the values
values, validations = forme_parse(@album).values_at(:values, :validations)
# Convert keys back to string as roda/plugins/forme_set transforms keys to symbols
# set_fields requires strings as keys
values.transform_keys!(&:to_s)
# Set the album.name field based on the form input
@album.set_fields(values, %w'name')
# Update album.artist association, use `active_support presence` here to avoid
# @album.artist = r.params["album"]["artist"].empty" ? nil : Artist[r.params["album"]["artist]
@album.artist = Artist[r.params["album"]["artist"].presence]
# TODO: does not work
@album.forme_validations.merge!(validations)
@album.artist.validate
@album.artist.save
end <%=
form(@album) do |f|
f.input(:name, key: "name", type: :text)
f.input(:artist, key: "artist")
end
%> I'm still not able to get the validation to work (rendering the form doesn't add any error elements). What I noticed is that upon form submission the payload will contain |
Beta Was this translation helpful? Give feedback.
-
Trying to get Frome to work with a model class which has a
many_to_one
association. I'm usingforme_set
to update all direct model attributes, which works fine.When adding a field to the form, from an associated model & using a nested_attribute, the select box renders fine and lists options, but storing the user input returns an error:
The documentation states that this is expected behavior:
However I couldn't find an example, and I'm unable to figure out how one would use forme_set & set_fields (I'm usually using the specs for digging up workable code).
Basically I'd need to create one form, some fields should use forme_set, some fields should be ignored and only be processed by a manual set_fields.
Beta Was this translation helpful? Give feedback.
All reactions