user659068
user659068

Reputation: 343

How to pass value from controller to model?

class Task < ActiveRecord::Base
  has_many :notes, :as => :notable,  :dependent => :destroy
  has_many :work_times, :dependent => :destroy
end

class WorkTime < ActiveRecord::Base
  belongs_to :task
end


class NotesController < ApplicationController


      end
    end
####

Any help please??

Upvotes: 0

Views: 632

Answers (3)

Kevin Davis
Kevin Davis

Reputation: 2718

As alluded to by a few of the other answers, you need an object of type WorkTime to pass the value to.

From the code you've posted it doesn't look like you've got such an instance. You can either find one (WorkTime.find.. ) or create a new one (WorkTime.new..)

It looks like you have an instance of a note (@note), though I'm not sure where that came from.. you might be able to fetch appropriate WorkTime objects using:

@note.task.work_times

or the first of these with:

@note.task.work_times.first

Upvotes: 1

tadman
tadman

Reputation: 211740

Since the relationship is a has_many you will need to work with a particular time, not the aggregate:

work_time = @task.work_times.last
work_time.start_time = Time.now
work_time.save!

In this case the last WorkTime record is selected and manipulated. Maybe you want to use the first, or select it with a condition:

work_time = @task.work_times.where(:active => true).first

There's a lot of ways to select the correct record to manipulate, but your question is somewhat vague.

If you're looking to create a new entry instead of modifying one, you might want to do this:

@task.work_times.create(:start_time => Time.now)

This is just exercising the ActiveRecord model relationship.

Upvotes: 1

Spyros
Spyros

Reputation: 48706

You would simply get the object and just change its value like :

user = User.first
user.username = 'changed_name'
user.save # and save it if you want

But, this is actually code that belongs to a model and should be wrapped by a model method.

Upvotes: 1

Related Questions