views:

111

answers:

3

In Rails 3, I am having a problem accessing a helper method from within a model

In my ApplicationController I have a helper method called current_account which returns the account associated with the currently logged in user. I have a project model which contains projects that are associated with that account. I have specified 'belongs_to :account' in my project model and 'has_many' in my account model. All of this seems to be working correctly and my projects are being associated with the right accounts.

However at the moment when I use 'Project.all', all of the project records are being returned as you would expect. I would like it to automatically filter the projects so that only those associated with the specified account are returned and I would like this to be the default behaviour

So I tried using 'default_scope'. The line in my model looks something like this

default_scope :order => :name, :conditions => ['account_id = ?', current_account.id]

This throws an error saying

Undefined local variable or method current_account for #

If I swap the call to current_account.id for an integer id - eg

default_scope :order => :name, :conditions => ['account_id = ?', 1]

Everything works correctly. How do I make my current_account method accessible to my model

Many Thanks

+3  A: 

You can't access the session from models. Instead, pass the account as a parameter to a named scope.

#controller
Model.my_custom_find current_account

#model.rb

named_scope :my_custom_find, lambda { |account| { :order => :name, :conditions => ['account_id = ?', account.id]}}

I haven't used rails 3 yet so maybe named_scopes have changed.

mark
`named_scope` is now deprecated, use `scope` instead.
jpemberthy
Thanks very much for that. But is there a way of making this default behaviour? I would like it so that when I use Project.all, by default it assumes that results should be restricted to a single account.
Addsy
+1  A: 

+1 for mark's answer. This should still work in Rails 3.

Just showing you the rails 3 way with scope and new query api:

scope :my_custom_find, lambda { |account| where(:account_id=>account.id).order(:name) }
cowboycoded
Thanks very much for that. But is there a way of making this default behaviour? I would like it so that when I use Project.all, by default it assumes that results should be restricted to a single account.
Addsy
A: 

You've got the association set up, so couldn't you just use:

@projects = current_account.projects.all

...in your controller?

I've not adjusted the syntax to be Rails 3 style as I'm still learning it myself.

Stephen Orr