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

Ransack

https://github.com/activerecord-hackery/ransack

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

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

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

A quick correction on Colin’s suggestion:

Good call, you are right. Thanks.

Colin