can't create partial objects with accepts_nested_attributes_for
Posted
by
Isaac Cambron
on Stack Overflow
See other posts from Stack Overflow
or by Isaac Cambron
Published on 2012-12-01T17:00:04Z
Indexed on
2012/12/01
17:03 UTC
Read the original article
Hit count: 169
ruby-on-rails
|ruby-on-rails-3
I'm trying to build a form that allows users to update some records. They can't update every field, though, so I'm going to do some explicit processing (in the controller for now) to update the model vis-a-vis the form. Here's how I'm trying to do it:
Family model:
class Family < ActiveRecord::Base
has_many :people, dependent: :destroy
accepts_nested_attributes_for :people, allow_destroy: true, reject_if: ->(p){p[:name].blank?}
end
In the controller
def check
edited_family = Family.new(params[:family])
#compare to the one we have in the db
#update each person as needed/allowed
#save it
end
Form:
= form_for current_family, url: check_rsvp_path, method: :post do |f|
= f.fields_for :people do |person_fields|
- if person_fields.object.user_editable
= person_fields.text_field :name, class: "person-label"
- else
%p.person-label= person_fields.object.name
The problem is, I guess, that Family.new(params[:family])
tries to pull the people out of the database, and I get this:
ActiveRecord::RecordNotFound in RsvpsController#check
Couldn't find Person with ID=7 for Family with ID=
That's, I guess, because I'm not adding a field for family id to the nested form, which I suppose I could do, but I don't actually need it to load anything from the database for this anyway, so I'd rather not. I could also hack around this by just digging through the params hash myself for the data I need, but that doesn't feel a slick. It seems nicest to just create an object out of the params hash and then work with it.
Is there a better way? How can I just create the nested object?
© Stack Overflow or respective owner