attr_accessor在accept_nested_attributes_for中无法访问
-
25-10-2019 - |
题
在我的付款页面上,有某些变量,例如card_number,我想从视图传递到模型,但我不想将它们存储在DB中。我通常可以通过简单地使用attr_accessor轻松实现这一目标,但是在这种情况下,该模型正在通过accams_nested_attributes_for中的参数传递,并且由于某种原因,params尚未通过:
在user.rb中我有
has_many :credit_cards
accepts_nested_attributes_for :credit_cards
在视图文件中,我有一个嵌套表单字段,类似:
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我有:
attr_accessor :test
before_create :show_me_test_param
private
def show_me_test_param
raise "#{test}"
end
现在,奇怪的是,当我尝试保存记录时,它只是返回一个空的异常。参数似乎并未通过accepts_nested_attributes_for从用户传递到CreditCard?
传递的参数是:
{"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"}}}
有人知道发生了什么事吗?是否接受attr_accessor的ancepts_nested_attributes__ Attributes_?
解决方案
过去,这使我搞砸了几次!嵌套对象的参数用键来到控制器上 model_name_attributes
将传递到控制器中模型的新或Update_Attributes方法。
因此您需要添加 :credit_card_attributes
给你 attr_accessor
允许该钥匙通过。
不隶属于 StackOverflow