开发者

accessing deeply nested params rails

I am writing a piece of code in my controller that is suposed to take the data a user inputs in the form of 00:00 and convert that into minutes before sending it to the model. The code I am using is pretty simple, just split the :duration parameter at the colon and multiply hours by 60 and add the minutes to that number. When I submit the for I get an error when it tries to perform split on a nil object. This must mean I am not accessing the parameter correctly but I am confused as to how I would navigate to a deeply nested parameter and cant seem to find any do开发者_JAVA百科cumentation regarding deeply nested parameters.

Here is my model organization:

log_entry >>
has many
workouts >>
has many 
workout_times, which has :duration as an attribute 

This is the code within my log_entries_controller:

def convert_duration
  hours, minutes = params[:log_entry][:workout][:workout_time][:duration].split(":")
  params[:log_entry][:workout][:workout_time][:duration] = (hours.to_i * 60 + minutes.to_i)
end

I have tried all the ways I could think of to write the params part but I cants seem to get it right. I am pretty new to rails/programming so there might be somthing totally obvious I am missing...

EDIT

Here is the log info of parameters past:

Parameters: {
  "commit" => "Save",
  "log_entry" => {
    "date(1i)" => "2011",
    "date(2i)" => "10",
    "date(3i)" => "13",
    "workouts_attributes" => {
      "0" => {
        "time_of_day" => "AM",
        "summary" => "",
        "workout_times_attributes" => {
          "0" => {
            "duration" => "2:00",
            "zone" => "1",
            "_destroy" => "false"
          }
        }
      }
    }
  },
  "authenticity_token"=>"zD6qS6jOSQ3/mRyH7RAgAzWYmwHub0+uBG1sjPVvkEY=",
  "utf8"=>"\342\234\223"
}


You could just assign the parameter you want to your model like so:

def save
  workout = Workout.new(params[:workout])
  workout.workout_time.duration = convert_duration(workout)  
end

Then in your convert_duration method do:

def convert_duration(workout)
  hours, minutes = workout.workout_time.duration.split(":")
  (hours.to_i * 60 + minutes.to_i)
end

In Ruby the last statement of a method is returned, so this would return your calculated duration back to the save method which will set the duration on the workout_time object for the workout object we created from the parameters passed to the method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜