Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Since there are actually multiple <code>avatar_assets</code> ( one for each size ), you have to keep it as a <code>has_many</code> association. </p> <pre><code>class User &lt; AR::B has_many :avatar_assets, :conditions =&gt; ['filename like ?' '%avatar%'], :class_name =&gt; 'Asset' named_scope :avatar_size, lambda { |size| { :conditions =&gt; [ "thumbnail = ?", size ] } } end </code></pre> <p>An alternative would be to put all the work in the named scope:</p> <pre><code>class User &lt; AR::B named_scope :avatar_for, lambda { |user, options| if options[:size] { :conditions =&gt; [ "filename like ? AND thumbnail = ?", user.login, options[:size] ] } else { :conditions =&gt; [ "filename like ?", user.login ] } end } end </code></pre> <p>this allows you to say</p> <pre><code>Asset.avatar_for(current_user, :size =&gt; :medium) </code></pre> <p>but is less cool when you find yourself saying</p> <pre><code>current_user.avatar_for( current_user, :size =&gt; :medium ) </code></pre> <p>you could add some <code>:avatar</code>, <code>:avatar?</code>, etc methods to User to clean this up.</p> <p>Personally I advise you to check out the Paperclip plugin and avoid these issues entirely.</p> <p><strong>EDIT:</strong></p> <p>Per your comment, to create a condition like "show me comments by avatar-having users", I'm not sure that will do it. You'd could make a relationship like so:</p> <pre><code>class Comment named_scope :with_avatars, :include =&gt; { :user =&gt; :avatar_assets }, :conditions =&gt; [ 'assets.thumbnail = ?', :thumb ] end </code></pre> <p><strong>EDIT:</strong></p> <p>Since you're only interested in caching, rather than conditions, we can drop the condition array:</p> <pre><code> named_scope :with_avatars, :include =&gt; { :user =&gt; :avatar_assets } </code></pre> <p>I revised the code above to be more workable. The key difference is to make the 'avatar'-ness of the assets easily queryable. If you can update your existing avatar_assets to have a filename including the pattern 'avatar-[login]', you can make the condition set static which is much cleaner than always having to search for the avatar based on the user login. Association extensions are another way to resolve this, however I don't think you'll be able to chain them or combine them with named scopes.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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