开发者

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??


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.


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.


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
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜