A quick correction on Colin's suggestion:

On Mon, Jul 13, 2015 at 2:44 AM, Colin Law <clan...@gmail.com> wrote:

> On 13 July 2015 at 01:10, j...@via.net <j...@via.net> wrote:
> > class Asset < ActiveRecord::Base
> >   belongs_to :site
> >
> >   # class variable :name
> >
> > end
> >
> > class Site < ActiveRecord::Base
> >   has_many :assets
> >
> >   # class var x, y, z
> >
> > end
> >
> > Is there a dynamic finder that will traverse the inner join:
> >
> > e.g. Site.find_by_asset_name("xyzzy")
>
> Asset.where( name: 'xyzzy').site
>

Asset.find_by(name: 'xyzzy').site

Because .where returns a collection, .find_by returns the first one found.

Asset.where(name: 'xyzzy').first = Asset.find_by(name: 'xyzzy')

(I make this same mistake a lot for some reason.)



> >
> > Can I get a list of sites where asset.name == "BAZ"
>
> Site.joins(:assets).where(assets: {name: "BAZ"})
>
> >
> > Can this be done in AR or do I have to resort to SQL?
>
> As you can see it can be done in AR.  It is very rare to have to
> resort to SQL in Rails.  If you do it often means you have not
> specified the associations correctly.
>
> Have a look at the rails guide on ActiveRecord Querying, and the other
> guides.  In fact I suggest you start by working right through a good
> tutorial such as railstutorial.org, which is free to use online.  That
> will show you the basics of Rails.
>
> Colin
>
> >
> > Thanks,
> >
> > Joe
> >
>

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/rubyonrails-talk/CAHUC_t-OutWp7JZYD-AodDsOri%2Bk%2Bgrk-S%3DgCWQbGeApwsqaHQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to