如何使用虚拟属性更新模型的属性?

我有一个名为UserPrice的模型,其表中包含属性:purchase_date (date_select)。 使用我的表单,我可以一次创建多个user_prices但为了方便用户,我在UserPrice模型中创建了一个名为:all_dates的虚拟属性,它也是一个date_select字段,它的作用是替换:purchase_dates因此用户只需要选择:all_dates日期的:all_dates字段。


问题与疑问

:all_dates字段未更新正在创建的user_prices的:purchase_date字段。 为了获取my :all_dates字段以更新我的新UserPrices:purchase_date字段,我需要UserPrices什么?

有没有人有关于如何做到这一点的任何提示?


参数

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

  class CreateUserPrices < ActiveRecord::Migration def self.up create_table :user_prices do |t| t.decimal :price t.integer :product_id t.date :purchase_date t.timestamps end end end 

我拿出了:purchase_date字段,因此它不在user_price循环中。

  :post do %>     up %>    class UserPrice  "DateTime", :mapping => %w(Time to_s), :constructor => Proc.new { |item| item }, :converter => Proc.new { |item| item } def user_prices @user_prices = Array.new() { UserPrice.new } end protected def save_all_dates_to_user_prices if !self.all_dates.nil? self.user_prices.each {|up| up.purchase_date = self.all_dates if up.new_record?} end end class UserPricesController  "Successfully added prices." else redirect_to :back, :notice => "Error, please try again." end end 

这是一个尝试在模型中做什么最好留给控制器的情况。 你在这里尝试做的就是从一个不直接与你的模型相关的参数自动分配创建的某个属性。 但是你甚至没有将任何额外的参数传递给模型 – 你从参数哈希的user_prices部分创建模型实例,但user_price子哈希不在任何地方使用。 在任何情况下,这是与模型相关的视图和操作更紧密相关的行为,因此请将其保留在控制器中。

试试这个:

  1. 抛出虚拟属性,摆脱整个after_save回调的东西
  2. 丢弃模型中的user_prices方法
  3. 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_price每个user_prices子哈希中。 用以下内容替换该操作中的第一行:

 @user_prices = params[:user_prices].values.collect do |attributes| UserPrice.new(attributes.merge(params[:user_price])) end 

我不确定为什么你甚至使用虚拟属性还有更多这个实现? 如果您只是想保存关联的模型,可能只需要在User模型中使用accepts_nested_attributes_for :user_prices

这很有效,许多开发人员都使用这种方法,所以很高兴知道在其他项目上工作以及最终可能会维护你的项目的人。

http://railscasts.com/episodes/196-nested-model-form-part-1

http://railscasts.com/episodes/197-nested-model-form-part-2