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 !
Tor Erik Linnerud
June 26, 2009, June 26, 2009 11:35, permalink
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
steved
July 5, 2009, July 05, 2009 18:55, permalink
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
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?