Rails newbie here! I'm attempting to create a form that allows User to add multiple Forecasts on one page. (Ideally, you would be able to enter an entire week of Forecasts at one time.) In the app, the two models are nested. (You can only get to Forecasts through a User.)
I modified the Forecast form and controller based on this response (also watched Railscast #196) ad while the form will now build any # of Forecast objects I need, it only saves the last one. What am I missing? Or what am I misunderstanding? Any help is really appreciated! I'm using Rails 3.2.6:
class Forecast < ActiveRecord::Base
attr_accessible :castdate, :level, :user_id
belongs_to :user
class User < ActiveRecord::Base
attr_accessible :defaultcast, :email, :password, :username, :name, :forecast_attributes
has_many :forecasts
accepts_nested_attributes_for :forecasts
In Forecast controller:
def new
@user = User.find(params[:user_id])
@forecast = @user.forecasts.build
@forecasts = Array.new(3) { @user.forecasts.build }
respond_to do |format|
format.html # new.html.erb
format.json { render json: @forecast }
end
end
Forecast _form:
<%= form_for(:forecasts, :url => user_forecasts_path(@user)) do |f| %>
(I attempted to use the suggested form_for([@user, :forecasts]) from the linked response above but received this error: undefined method `model_name' for Symbol:Class )
<% @forecasts.each do |forecast| %>
<%= fields_for forecast do |r| %>
<div class="field">
<%= r.label "Date" %><br />
<%= r.date_select :castdate, :start_year => Time.now.year,
:use_two_digit_numbers => true %>
</div>
<div class="field">
<%= r.label "Grump Level" %><br />
<%= r.number_field :level, :min => 0, :max => 10 %>
</div>
<% end %>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>