<?xml version="1.0" encoding="UTF-8"?>
<code>
  <code>@team.statements.scoped({ 
               :select =&gt; "statements.*, users.first_name",
               :joins =&gt; "INNER JOIN users ON users.id = statements.user_id",
               :order =&gt; 'RAND()',
               :limit =&gt; '100'}).to_json</code>
  <comment>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?
</comment>
  <created-at type="datetime">2009-06-24T15:38:44+00:00</created-at>
  <id type="integer">931</id>
  <language>Ruby</language>
  <permalink>named-scopes-in-relations</permalink>
  <refactors-count type="integer">2</refactors-count>
  <title>Named Scopes in Relations</title>
  <trackback-url></trackback-url>
  <updated-at type="datetime">2009-07-05T18:56:04+00:00</updated-at>
  <user-id type="integer">1228</user-id>
  <refactors type="array">
    <refactor>
      <code>If you define a named scope on Statement like this:

class Statement &lt; ActiveRecord::Base

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

Then you can do @team.statements.random</code>
      <code-id type="integer">931</code-id>
      <comment></comment>
      <created-at type="datetime">2009-06-26T11:35:01+00:00</created-at>
      <id type="integer">174912</id>
      <language>Ruby</language>
      <rating type="integer">0</rating>
      <ratings-count type="integer">0</ratings-count>
      <title>On Named Scopes in Relations</title>
      <user-id type="integer" nil="true"></user-id>
      <user-name>Tor Erik Linnerud</user-name>
      <user-website>tel.jklm.no</user-website>
    </refactor>
    <refactor>
      <code>class Team &lt; ActiveRecord::Base

  has_many :statements do
    def random
      find(:all, &lt;other finder options)
    end
  end

end

Team.first.statements.random</code>
      <code-id type="integer">931</code-id>
      <comment>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.</comment>
      <created-at type="datetime">2009-07-05T18:55:58+00:00</created-at>
      <id type="integer">188881</id>
      <language>Ruby</language>
      <rating type="integer">0</rating>
      <ratings-count type="integer">0</ratings-count>
      <title>On Named Scopes in Relations</title>
      <user-id type="integer" nil="true"></user-id>
      <user-name>steved</user-name>
      <user-website></user-website>
    </refactor>
  </refactors>
</code>
