Active Record question

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”)

Can I get a list of sites where asset.name == “BAZ”

Can this be done in AR or do I have to resort to SQL?

Thanks,

Joe

On 13 July 2015 at 01:10, [email protected] [email protected] wrote:

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

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

Ransack

Seems like a promising for your usecase. Take a look at it.

On Mon, Jul 13, 2015 at 5:40 AM, [email protected] [email protected] wrote:

class var x, y, z

To view this discussion on the web visit

https://groups.google.com/d/msgid/rubyonrails-talk/7f72701d-cd1c-4219-b4e3-1aa5b643a895%40googlegroups.com

https://groups.google.com/d/msgid/rubyonrails-talk/7f72701d-cd1c-4219-b4e3-1aa5b643a895%40googlegroups.com?utm_medium=email&utm_source=footer

.
For more options, visit https://groups.google.com/d/optout.


Regards
Vineeth B S

A quick correction on Colin’s suggestion:

On Mon, Jul 13, 2015 at 2:44 AM, Colin L. [email protected] wrote:

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.)

On 13 July 2015 at 19:20, tamouse pontiki [email protected]
wrote:

end
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’)

Good call, you are right. Thanks.

Colin