2011-10-23 20 views
0

我在窗體上使用了一個名爲: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 
+1

一個問題,我看到:第一個參數'date_select '必須是一個對象的名字(你的user_price),第二個應該是'all_dates'。另外,看看生成的HTML看起來像什麼? – Zabba

+0

@Zabba謝謝,我相信現在是正確的,現在查看我的編輯。錯誤是不同的。 – LearningRoR

回答

1

回覆:爲什麼收到錯誤未定義的方法`user_prices'爲...

答:您需要定義方法user_prices

由於您命名了模型(對象)UserPrice,通常user_price將用於表示模型的一個實例。

您需要重新考慮user_prices表示一個UserPrice對象/記錄數組?或者是其他東西?

已添加您是否想要方法save_all_dates_to_user_prices遍歷所有UserPrice記錄?

如果是這樣的話:

  • 你可能想save_all_dates_to_user_prices是一個類的方法,因爲它會被處理之類的多個實例。

  • 該方法需要首先加載一個包含所有當前記錄的數組。用類方法來執行此發現或scope

相關問題