我有一个名为UserPrice
的模型,其表中包含属性:purchase_date
(date_select)。使用我的表单,我可以一次创建多个user_prices但为了方便用户,我在名为UserPrice
的{{1}}模型中创建了一个虚拟属性,该属性也是date_select字段,其作用是替换{ {1}}因此用户只需选择日期的:all_dates
字段。
问题&问题
:purchase_dates
字段未更新正在创建的user_prices的:all_dates
字段。 我需要做些什么才能让我的:all_dates
字段更新新:purchase_date
的{{1}}字段?
有没有人知道如何做到这一点?
参数
:all_dates
代码
:purchase_date
我取出了UserPrices
字段,因此它不在user_price循环中。
Parameters:
"user_price"=> {
"all_dates(2i)"=>"10",
"all_dates(3i)"=>"27",
"all_dates(1i)"=>"2011"
},
"user_prices"=>
{
"0"=>{"product_name"=>"Item1", "store"=>"Apple Store","price"=>"6"},
"1"=>{"product_name"=>"Item2", "store"=>"Apple Store", "price"=>"7"}
},
"commit"=>"Submit"}
答案 0 :(得分:2)
这是一个尝试在模型中做什么最好留给控制器的情况。你在这里尝试做的就是从一个不直接与你的模型相关的参数自动分配创建的某个属性。但是你甚至没有将任何额外的参数传递给模型 - 你从参数哈希的user_prices
部分创建模型实例,但user_price
子哈希不在任何地方使用。在任何情况下,这是与模型相关的视图和操作更紧密相关的行为,因此请将其保留在控制器中。
试试这个:
after_save
回调内容user_prices
方法all_dates
醇>
然后您的参数哈希应如下所示:
purchase_date
剩下要做的就是将单个{"user_price"=> {
"purchase_date(2i)"=>"10",
"purchase_date(3i)"=>"27",
"purchase_date(1i)"=>"2011"
},
"user_prices"=>
{
"0"=>{"product_name"=>"Item1", "store"=>"Apple Store","price"=>"6"},
"1"=>{"product_name"=>"Item2", "store"=>"Apple Store", "price"=>"7"}
}}
属性合并到user_price
操作中的每个user_prices
子哈希中。用以下内容替换该操作中的第一行:
create_multiple
答案 1 :(得分:1)
我不确定为什么你甚至使用那个虚拟属性还有更多这个实现?如果您只是想保存关联的模型,可能只需要在用户模型中使用accepts_nested_attributes_for :user_prices
这很有效,很多开发人员都使用这种方法,所以很高兴知道在其他项目上工作以及最终可能会维护你的项目的人。