Question

On my payments page there are certain variables such as card_number that I want to pass from the View to the Model but I do not want to store them in the db. I can usually easily achieve this by simply using attr_accessor but in this case the model is being passed in params through accepts_nested_attributes_for and for some reason the params are not being passed through:

in User.rb i have

  has_many :credit_cards

  accepts_nested_attributes_for :credit_cards

in the view file i have a nested form field, something like:

  blah blah
  <h2>Credit card</h2>
  <%= f.fields_for :credit_cards do |builder| %>
    <%= render "credit_card_fields", :f => builder %>
  <% end %>

  inside that
  <p>
    <%= f.label :test %><br />
    <%= f.text_field :test %>
  </p>

now back in credit_card.rb i have:

attr_accessor :test

before_create :show_me_test_param

private

def show_me_test_param
  raise "#{test}"
end

Now the strange thing is that when I try to save a record, it simply returns an empty exception. The param does not seem to have been passed through from User to CreditCard through accepts_nested_attributes_for?

The param being passed in is:

{"email"=>"name@example.com", "password"=>"pass123", "password_confirmation"=>"pass123", "credit_cards_attributes"=>{"0"=>{"test"=>"helllo this is the second attempt", "name_on_card"=>"first lastname", "card_number"=>"987498742897", "card_verification_value"=>"232", "expiry_date"=>"2141"}}}

Does anyone know whats going on? Does accepts_nested_attributes_for work with attr_accessor?

Was it helpful?

Solution

This has messed me up several times in the past! Params for nested objects come to the controller with the key model_name_attributes which gets passed to the new or update_attributes method of the model in the controller.

So you'll need to add :credit_card_attributes to your attr_accessor to allow that key to be passed in.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top