问题
Here's my controller
class ActivitiesController < ApplicationController
def exercises
if current_user.userprofile.present? #chef whether there is a userprofile object
@weeknum = current_user.userprofile.week
@dayly_activity = Activity.where(:week => 1, :day => 'Monday').first
end #end check userprofile
end
def updatexercises
respond_to do | format |
@dayly_activity = Activity.where(:week => 1, :day => 'Monday').first
@dayly_activity.update_attributes(params[:@dayly_activity])
@dayly_activity.save
format.html { render action: "exercises" }
end
end
end
And my template
<h1>WEEKLY EXERCICES</h1>
Day : <%= @dayly_activity.day %>
<%= form_for(@dayly_activity, :url => { :action => "updatexercises" }) do | f | %>
<table>
<tr>
<td>Jogging:</td>
<td>
<% list = (0..20).to_a %>
<%= f.select :jog, list %>
x 0.1 km
</td>
</tr>
<tr>
<td>Bicycling:</td>
<td>
<% list = (0..10).to_a %>
<%= f.select :bicycl, list %>
km
</td>
</tr>
<tr>
<td>Push ups:</td>
<td>
<% list = (0..20).to_a %>
<%= f.select :pushups, list %>
x 10 times
</td>
</tr>
<tr>
<td colspan = "2"><%= f.submit %></td>
</tr>
</table>
<% end %>
When I click the button, the Daily+activity object is not being saved. Am I missing some thing
EDIT
I've tried to hard code this way and it saving to the database.
@dayly_activity.jog = 17
@dayly_activity.pushups = 13
@dayly_activity.save
Obviously, the problem must be with the update_attributes
回答1:
You need to use params[:dayly_activity]
(drop the @ sign).
Also, I would put these two lines :
@dayly_activity = Activity.where(:week => 1, :day => 'Monday').first
@dayly_activity.update_attributes(params[:dayly_activity])
Outside of your respond_to
block (put them on top of it).
You can also drop the @dayly_activity.save
, update_attributes do it automatically and will returns true/false if it works/fails.
回答2:
You have error in [:@dayly_activity]
And in that code
@dayly_activity.update_attributes(params[:@dayly_activity])
@dayly_activity.save
save
is useless. update_attributes
saving the record.
It better to check result of update_attributes
. So you can catch validation errors.
For example
if @dayly_activity.update_attributes(params[:dayly_activity])
redirect_to dayli_activity_path, :notice => "Updated"
else
render :edit
end
来源:https://stackoverflow.com/questions/13535945/update-attributes-is-not-working