santuxus
santuxus

Reputation: 3702

how to make rails strong_parameters + nested_attributes + serialize work?

I'm having hard time to get rails 4 work with nested_attributes and serialize. I have:

class Client < ActiveRecord::Base
  belongs_to :event
  serialize :phones
end


class Event < ActiveRecord::Base
  has_one :client
end


class EventsController < ApplicationController

  ...

  def event_params
    params.permit(client_attributes: [:phones])
  end
end

When I pass event:

{client_attributes: { phones: 'string'}}

it works, but when I try

{client_attributes: { phones: [{phone_1_hash},{phone_2_hash}]}}

I get 'Unpermitted parameters: phones' message and field is not saved...

I've tried to use

class EventsController < ApplicationController

  ...

  def event_params
    params.permit(client_attributes: [phones:[]])
  end
end

or

class Client < ActiveRecord::Base
  belongs_to :event
  serialize :phones, Array
end

but so far nothing helped. Any suggestions would be appreciated. Thanks!

Upvotes: 2

Views: 1543

Answers (1)

santuxus
santuxus

Reputation: 3702

Pfff - finally got it... With strong parameters no unknown keys can pass, so solution here was:

class EventsController < ApplicationController

  ...

  def event_params
    params.permit(client_attributes: [ {phones: [:number, :type]}])
  end
end

Based on http://edgeapi.rubyonrails.org/classes/ActionController/Parameters.html#method-i-permit-21

Hope it helps someone.

I could specify keys in my serialisable field here, but what with user added keys? Is serialised field usable with strong parameters at all? (this probably should be a new question...)

Upvotes: 6

Related Questions