# Calling a models function via a link

**URL:** <https://www.ruby-forum.com/t/calling-a-models-function-via-a-link/182379>\
**Category:** Rails\
**Created:** [January 27, 2010, 10:30am UTC](https://www.ruby-forum.com/t/calling-a-models-function-via-a-link/182379 "2010-01-27T10:30:01Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![brianp](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/94ad74/32.png) [@brianp](https://www.ruby-forum.com/u/brianp)\
**Post date:** [January 27, 2010, 10:30am UTC](https://www.ruby-forum.com/t/calling-a-models-function-via-a-link/182379/1 "2010-01-27T10:30:01Z")

</div>

Hey,

If i have a function in my model:  
def mark\_sold  
self.update\_attribute(:market\_status, ‘sold’)  
end

Is it possible for this to be called via an on page link?

Then I’d like to ajax it so a user could just scroll down a list  
clicking all links to “mark as sold” as he comes across old inventory.

Thanks,  
brianp

---

<div class="post-metadata">

**Author:** ![brianp](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/94ad74/32.png) [@brianp](https://www.ruby-forum.com/u/brianp)\
**Post date:** [January 27, 2010, 11:12am UTC](https://www.ruby-forum.com/t/calling-a-models-function-via-a-link/182379/2 "2010-01-27T11:12:10Z")

</div>

Quoting brianp [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid):

> clicking all links to “mark as sold” as he comes across old inventory.

Browser requests always are to controller methods. Any other way you  
are  
fighting Rails’ MVC opinioned structure.

Add a method to a controller and the route to config/routes.rb:

def mark\_sold  
model = Model.find(params[:id])  
model.mark\_sold  
render :partial =\> …, :object =\> model  
end

The render should generate the HTML for the changed model instance that  
the  
AJAX will replace.

HTH,  
Jeffrey

---

<div class="post-metadata">

**Author:** ![brianp](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/94ad74/32.png) [@brianp](https://www.ruby-forum.com/u/brianp)\
**Post date:** [January 27, 2010, 11:16am UTC](https://www.ruby-forum.com/t/calling-a-models-function-via-a-link/182379/3 "2010-01-27T11:16:51Z")

</div>

Thanks Jeffrey,

I had a good feeling this is how it needed to be done. But felt like I  
was bloating my controller. Now I’m happy knowing I was originally  
going in the right direction.

Thanks again.  
brianp
