在 accept_nested_attributes_for 中无法访问 attr_accessor [英] attr_accessor not accessible in accept_nested_attributes_for

查看:36
本文介绍了在 accept_nested_attributes_for 中无法访问 attr_accessor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的支付页面上,我想将某些变量(例如 card_number)从视图传递到模型,但我不想将它们存储在数据库中.我通常可以通过简单地使用 attr_accessor 轻松实现这一点,但在这种情况下,模型正在通过 accepts_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. 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:

在 User.rb 我有

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>

现在回到credit_card.rb我有:

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

现在奇怪的是,当我尝试保存记录时,它只是返回一个空异常.参数似乎没有通过 accepts_nested_attributes_for 从 User 传递到 CreditCard?

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?

传入的参数是:

{"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"}}}

有谁知道这是怎么回事吗?accepts_nested_attributes_for 是否与 attr_accessor 一起使用?

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

推荐答案

这在过去让我搞砸了好几次!嵌套对象的参数通过键 model_name_attributes 到达控制器,该键被传递给控制器​​中模型的 new 或 update_attributes 方法.

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.

因此您需要将 :credit_card_attributes 添加到您的 attr_accessor 以允许传入该密钥.

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

这篇关于在 accept_nested_attributes_for 中无法访问 attr_accessor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆