简体   繁体   English

attr_accessor在accept_nested_attributes_for中无法访问

[英]attr_accessor not accessible in accept_nested_attributes_for

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. 在我的付款页面上有一些变量,例如card_number,我想从View传递给Model,但我不想将它们存储在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: 我通常可以通过简单地使用attr_accessor轻松实现这一点,但在这种情况下,模型通过accepts_nested_attributes_for传递给params,并且由于某种原因,params没有被传递:

in User.rb i have 在User.rb我有

  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: 现在回到credit_card.rb我有:

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? 该参数似乎没有通过accepts_nested_attributes_for从User传递给CreditCard?

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? accepts_nested_attributes_for是否适用于attr_accessor?

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. 嵌套对象的参数使用键model_name_attributes传递给控制器​​,该键将传递给控制器​​中model_name_attributes的new或update_attributes方法。

So you'll need to add :credit_card_attributes to your attr_accessor to allow that key to be passed in. 因此,您需要将:credit_card_attributes添加到attr_accessor以允许传入该密钥。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM