Passing information from the controller to model
Oct 11, 2008
A refresher for passing information only available to the controller to a model.
Firstly you will need set up attr_accessor on the model to receive the object or value from the controller.
class Model < ActiveRecord::Base ... attr_accessor :current_user ... end
The controller can easily pass an object or value as set up with attr_accessor by taking an instances of the model and using the virtual attribute pass in the object.
class CompaniesController < ApplicationController
...
def create
@company = Company.new
@company.current_user = current_user
...
end
end
The value is passed in from the controller can now be accessed within the model using the virtual attribute as the instance variable @current_user. Please note: This can also be done by defining methods
def current_user
...
end
def current_user=(user)
@current_user = user
end
Posted by Thomas Cowell
© Copyright 2008 Eight Square Limited. All Rights Reserved.
before_save and after_save trouble when saving an associated object