Note that there are some explanatory texts on larger screens.

plurals
  1. POChange a finder method w/ parameters to an association
    text
    copied!<p>How do I turn this into a has_one association? </p> <p>(Possibly has_one + a named scope for size.)</p> <pre><code>class User &lt; ActiveRecord::Base has_many :assets, :foreign_key =&gt; 'creator_id' def avatar_asset size = :thumb # The LIKE is because it might be a .jpg, .png, or .gif. # More efficient methods that can handle that are OK. ;) self.assets.find :first, :conditions =&gt; ["thumbnail = '#{size}' and filename LIKE ?", self.login + "_#{size}.%"] end end </code></pre> <p>EDIT: Cuing from AnalogHole on Freenode #rubyonrails, we can do this:</p> <pre><code> has_many :assets, :foreign_key =&gt; 'creator_id' do def avatar size = :thumb find :first, :conditions =&gt; ["thumbnail = ? and filename LIKE ?", size.to_s, proxy_owner.login + "_#{size}.%"] end end </code></pre> <p>... which is fairly cool, and makes syntax a bit better at least.</p> <p>However, this still doesn't behave as well as I would like. Particularly, it doesn't allow for further nice find chaining (such that it doesn't execute this find until it's gotten all its conditions).</p> <p>More importantly, it doesn't allow for use in an :include. Ideally I want to do something like this:</p> <pre><code>PostsController def show post = Post.get_cache(params[:id]) { Post.find(params[:id], :include =&gt; {:comments =&gt; {:users =&gt; {:avatar_asset =&gt; :thumb}} } ... end </code></pre> <p>... so that I can cache the assets together with the post. Or cache them at all, really - e.g. <code>get_cache(user_id){User.find(user_id, :include =&gt; :avatar_assets)}</code> would be a good first pass.</p> <p>This doesn't actually work (self == User), but is correct in spirit:</p> <pre><code>has_many :avatar_assets, :foreign_key =&gt; 'creator_id', :class_name =&gt; 'Asset', :conditions =&gt; ["filename LIKE ?", self.login + "_%"] </code></pre> <p>(Also posted on <a href="http://refactormycode.com/codes/900-change-a-finder-method-w-parameters-to-an-association" rel="nofollow noreferrer">Refactor My Code</a>.)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload