update_attributes is not working

不羁岁月 提交于 2020-01-06 06:59:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!