Rails - Strong params, and creating a new resource via nested attributes for a delegated association? -
my rails 4 app fundraising tool bike ride. user can create riderreg(istration), , user has associated mailingaddress, delegated user via riderreg.
the associations seem work in console, i'm getting thrown strong params, , controller won't take nested attributes riderreg's mailingaddress -- because mailingaddress associated user.
you may wonder - why users , riders separate models? because users can donors and/or riders -- users whether riders or no need addresses.
anyhoo -- allow me add together code examples.
class riderreg < activerecord::base belongs_to :rider, :class_name => "user" delegate :first_name, :last_name, :title, :full_name, :receipts, :mailing_address, to: :rider, allow_nil: true, prefix: false # accepts_nested throws error - how else allow strong params? accepts_nested_attributes_for :mailing_address end class user < activerecord::base has_one :rider_reg, :foreign_key => :rider_id has_one :mailing_address, :as => :addressable accepts_nested_attributes_for :mailing_address end class riderregscontroller < applicationcontroller private def rider_reg_params params.require(:rider_reg).permit(:ride_option, :primary_phone, :secondary_phone, :birthdate, :goal, :bio, :accept_terms, :photo, :mailing_address_attributes => [:line1, :line2, :city, :state, :zip]) end end
my params hash submit via form_helper looks this:
parameters: {"utf8"=>"✓", "authenticity_token"=>"pbdqe/f4s+dlhroy+zdvh6ms0mmo0fur88uie4ojjqq=", "rider_reg"=>{"ride_option"=>"original track", "mailing_address"=>{"line1"=>"asdfasfd", "line2"=>"", "city"=>"asdfsadf", "state"=>"alaska", "zip"=>""}, "primary_phone"=>"", "secondary_phone"=>"", "bio"=>"", "goal"=>"0.0"}, "rider_reg_month"=>"1", "rider_reg_year"=>"1934", "rider_reg_day"=>"1", "commit"=>"create rider reg"}
and server log tells me this:
unpermitted parameters: mailing_address
so -- after couple of days of headbanging - think may time admit ignorance here. advice much appreciated! thanks!
its because there no association between riderreg , mailingaddress.
there 2 ways can go around this.
add relationship betweenriderreg
, mailingaddress
switch riderreg
, rider
relationship , foreign key. take nested attributes rider
, have view like:
= f.fields_for :rider |uf| # user fields here. = uf.fields_for :mailing_address |maf| # mailing address fields here
then adjust strong params take user.
ruby-on-rails ruby-on-rails-4 strong-parameters
No comments:
Post a Comment