我在窗體上使用了一個名爲:all_dates
的虛擬屬性。此字段的要點是將我的UserPrice
型號的:purchase_date
屬性替換爲我的:all_dates
字段的日期。這是因爲用戶無需更改所有要在表單上創建的user_price記錄的:purchase_date
(它們可以創建最多5個記錄),所以它假設要更新user_prices與從:all_dates
字段給出的日期。獲取NoMethodError,我該如何定義這個方法?
問題
不幸的是創造1至5條記錄user_prices的,我得到一個NoMethodError因爲:all_dates
領域:
NoMethodError (undefined method `user_prices' for #<UserPrice:0x485d918>):
app/models/user_price.rb:54:in `save_all_dates_to_user_prices'
app/controllers/user_prices_controller.rb:27:in `each'
app/controllers/user_prices_controller.rb:27:in `create_multiple'
UPDATE
我把這個放在我的使用中,擺脫了NoMethodError rPrice型號:
def user_prices
@user_prices = Array.new() { UserPrice.new }
end
但是因爲:all_dates
字段不更新我的UserPrice :purchase_date
字段是不正確的。有沒有人有任何想法?
問題
如何定義的方法user_prices
? 我猜它假設能夠循環UserPrice的幾個新記錄,但是這是如何完成的?
代碼
這種形式就像一個嵌套形式,但不是使用兩個或更多的車型其只使用一個單一的模型,它是我的UserPrice生成表單上更多的記錄,在我的情況5個新的。
<%= 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 "add_store_price_fields", :f => up %>
<% end %>
<% end %>
<% end %>
class UserPrice < ActiveRecord::Base
attr_accessible :price, :product_name, :all_dates
attr_accessor :all_dates
after_save :save_all_dates_to_user_prices
protected
def save_all_dates_to_user_prices
self.user_prices.each {|up| up.purchase_date = self.all_dates if up.new_record?}
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
一個問題,我看到:第一個參數'date_select '必須是一個對象的名字(你的user_price),第二個應該是'all_dates'。另外,看看生成的HTML看起來像什麼? – Zabba
@Zabba謝謝,我相信現在是正確的,現在查看我的編輯。錯誤是不同的。 – LearningRoR