Model scope and preventing repeated code


I have an issue with my implementation of a feature which need to use a
Model find statement to lookup values based on specific conditions:

I have a method called ‘get_messages’ which needs to get values from the
database depending on the called scope. So,
‘Messages.inbox.get_messages’, needs to only return values from the
database if the :recipient field in the database matches a current
session variable.

I tried this: (In my model)

scope :inbox, :conditions => {:recipient => @sessionId}
scope :sent, :conditions => {:sender => @sessionId}
def self.get_messages
messages = find(:all, :order => ‘id desc’)
return messages

then calling: (in controller)
messages = Messages.inbox.get_messages

messages = Messages.sent.get_messages

…but having the Model inherit the class variable from my controller
goes against the concepts of MVC.

Is there a way that I can achieve this without having to create multiple
methods in my Model to do the different conditional statements which I

I.e. NOT Having to make a method which is called get_inbox_messages and
get_sent_messages and then having the relevant recipient = or sender =
conditional statements in each one.


On 17 February 2011 17:49, Tom J. [email protected] wrote:

session variable.

I tried this: (In my model)

scope :inbox, :conditions => {:recipient => @sessionId}

Use a scope that takes a parameter, pass the id when you call it and
use the lambda construct to implement it.
has examples of how to do this.


This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs