Bfca16459c82a7836c3d5c8d79f0b640

I have two models: Teams and Statements. A statement belongs to a team. When I try to apply a scope to the relation - I can do this with anonymous scopes. Is there a possibility to define a named scope for a relation? When I define it in my Statement Model, it will say method_is missing. Any hints?

1
2
3
4
5
@team.statements.scoped({ 
               :select => "statements.*, users.first_name",
               :joins => "INNER JOIN users ON users.id = statements.user_id",
               :order => 'RAND()',
               :limit => '100'}).to_json

Refactorings

No refactoring yet !

C5d3ed543aa6ca59843aaca55f9ee2c1

Tor Erik Linnerud

June 26, 2009, June 26, 2009 11:35, permalink

No rating. Login to rate!
1
2
3
4
5
6
7
8
9
10
11
12
If you define a named scope on Statement like this:

class Statement < ActiveRecord::Base

named_scope :random{ 
     :select => "statements.*, users.first_name",
      :joins => "INNER JOIN users ON users.id = statements.user_id",
      :order => 'RAND()',
      :limit => '100'}).to_json
end

Then you can do @team.statements.random
Avatar

steved

July 5, 2009, July 05, 2009 18:55, permalink

No rating. Login to rate!

Tor's refactoring is probably best, but if you wanted to restrict the scoping to the association you can write a method on the association.

1
2
3
4
5
6
7
8
9
10
11
class Team < ActiveRecord::Base

  has_many :statements do
    def random
      find(:all, <other finder options)
    end
  end

end

Team.first.statements.random

Your refactoring





Format Copy from initial code

or Cancel