# Passing a variable from controller to model

**URL:** <https://www.ruby-forum.com/t/passing-a-variable-from-controller-to-model/100337>\
**Category:** Rails\
**Created:** [July 28, 2006, 1:21pm UTC](https://www.ruby-forum.com/t/passing-a-variable-from-controller-to-model/100337 "2006-07-28T13:21:31Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![samonderous](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/3da27b/32.png) [@samonderous](https://www.ruby-forum.com/u/samonderous)\
**Post date:** [July 28, 2006, 1:21pm UTC](https://www.ruby-forum.com/t/passing-a-variable-from-controller-to-model/100337/1 "2006-07-28T13:21:31Z")

</div>

Hi,

How do I pass a variable from my action into a model before saving the  
model. I’d like the model instance to have access to this variable to  
do some work before saving the model instance but the variable is not  
part of the model itself.

Thanks,

Sam

---

<div class="post-metadata">

**Author:** ![samonderous](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/3da27b/32.png) [@samonderous](https://www.ruby-forum.com/u/samonderous)\
**Post date:** [July 28, 2006, 2:45pm UTC](https://www.ruby-forum.com/t/passing-a-variable-from-controller-to-model/100337/2 "2006-07-28T14:45:33Z")

</div>

On 7/28/06, Sam D. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> Hi,
> 
> How do I pass a variable from my action into a model before saving the  
> model. I’d like the model instance to have access to this variable to  
> do some work before saving the model instance but the variable is not  
> part of the model itself.

In your model class, put an attr\_accessor :foo, then simply set it  
using e.g. model\_obj.foo = 42 in your controller and access via foo in  
yout model.

martin

---

<div class="post-metadata">

**Author:** ![samonderous](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/3da27b/32.png) [@samonderous](https://www.ruby-forum.com/u/samonderous)\
**Post date:** [July 28, 2006, 3:11pm UTC](https://www.ruby-forum.com/t/passing-a-variable-from-controller-to-model/100337/3 "2006-07-28T15:11:48Z")

</div>

Create a Model Object

Suppose the Model’s name is form.rb

in the controller, create an object for this model  
form\_object = Form.new

```
now assign an element to this object.
form_object['element1'] = "Hi this is the .............."

now call the method in the model which is defined belw.
form_object.validate_this

```

in the model Form. …

```
define a method like validate_this
def validate_this
    puts "The variable is #{element1}"
end

```

now u can access this variable in this method

Regards,  
Anand
