Model scope and preventing repeated code

Hi,

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:

Example:
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
end

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

or
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
need.

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.

Cheers.

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.
http://api.rubyonrails.org/classes/ActiveRecord/NamedScope/ClassMethods.html
has examples of how to do this.

Colin