I am using a virtual attribute called :all_dates on my form . The point of this field is to replace the :purchase_date attribute of my UserPrice model with the date of my :all_dates field. The reason for this is so user’s don’t have to change the :purchase_date of all of the user_price records they want to create on the form (they can create a maximum of 5), so what it suppose to do is update the columns of the user_prices with the date that is given from the :all_dates field.
Problem
Unfortunately on creating 1 to 5 records of user_prices, I get a NoMethodError because of the :all_dates field:
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
I got rid of the NoMethodError by putting this in my UserPrice model:
def user_prices
@user_prices = Array.new() { UserPrice.new }
end
But that isn’t correct because the :all_dates field doesn’t update my UserPrice :purchase_date fields. Does anyone have any ideas?
Question
How do I define the method user_prices?
I am guessing its suppose to be able to loop several new records of UserPrice but how is that done?
Code
This form acts like a nested form but instead of using two or more models its just using one single model which is my UserPrice to generate more records on the form, in my case being 5 new ones.
<%= 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
I Took a totally different approach and was still able to get the same results in this Question: How to update a model's attribute with a virtual attribute?