Reputation: 8587
In my controller I have this:
def hours_create
@hour = params[:hour].map { |hour_attrs| Hour.create(hour_attrs) }
if @hour.save
redirect_to :back, notice: "hour created."
else
render :new
end
end
The error is coming from @hour.save
, but not sure what to replace it, because I need to redirect the page somehow when item is saved into my database?
Why is there this error?
Thanks
Upvotes: 0
Views: 3689
Reputation: 107728
This error is happening because map
returns an array, and you're attempting to call save
on that. Arrays within Ruby do not have the method save
defined, hence the error.
Why are you trying to save
anyway? create
will validate the record and save it to the database if it's valid. You might want to use create!
instead and rescue the ActiveRecord::RecordInvalid
error that's thrown when that fails:
def hours_create
begin
params[:hour].each { |hour_attrs| Hour.create!(hour_attrs) }
rescue ActiveRecord::RecordInvalid
render :new
else
redirect_to :back, notice: "hour created."
end
end
Why is this action called hours_create
? This is a code smell imo. It sounds like it should be in a controller of its own called Hours
, which itself has a create
method.
Upvotes: 5