我有一个名为UserPrice
其具有属性:purchase_date
(a date_select) 在其表中。使用我的表单,我可以一次创建多个 user_prices,但为了用户方便,我在我的表单中创建了一个虚拟属性UserPrice
模型称为:all_dates
这也是一个 date_select 字段,它的作用是替换:purchase_dates
所以用户只需选择:all_dates
日期字段。
问题与疑问
The :all_dates
字段没有更新:purchase_date
正在创建的 user_prices 字段。我需要做什么才能获得我的:all_dates
字段来更新: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"}
Code
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 循环内部。
<%= form_tag create_multiple_user_prices_path, :method => :post do %>
<%= date_select("user_price", "all_dates" ) %>
<% @user_prices.each_with_index do |user_price, index| %>
<%= fields_for "user_prices[#{index}]", user_price do |up| %>
<%= render "user_price_fields", :f => up %>
<% end %>
<% end %>
<% end %>
class UserPrice < ActiveRecord::Base
attr_accessible :price, :product_name, :purchase_date, :all_dates, :store
attr_accessor :all_dates
after_save :save_all_dates_to_user_prices
composed_of :all_dates, :class_name => "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 < ApplicationController
def new
@user_prices = Array.new(5) { UserPrice.new }
end
def create_multiple
@user_prices = params[:user_prices].values.collect { |up| UserPrice.new(up) }
if @user_prices.all?(&:valid?)
@user_prices.each(&:save!)
redirect_to :back, :notice => "Successfully added prices."
else
redirect_to :back, :notice => "Error, please try again."
end
end