views:

117

answers:

2

anyone know how I would write that query with AR?

select *, (m.user_id=1) as member from band b join memberships m on m.band_id = g.id;

Thanks in advance.

+7  A: 

The assumption here is that you have something that looks like this:

class Band < ActiveRecord::Base
  has_many :memberships
  has_many :users, :through => :memberships
end

class User < ActiveRecord::Base
  has_many :memberships
  has_many :bands, :through => :memberships
end

class Membership < ActiveRecord::Base
  belongs_to :user
  belongs_to :band
end

In which case, you can perform this query easily.

user = User.find(1)
user.bands

Your question is quite vague, however, so if this isn't what you're looking for please considering expanding your question with some more details. You are also referencing an alias "g" in your question which is never defined.

jdl
Please read my question better, of course I know how to has_many through. What I'm trying to do is make my query return a custom boolean field "(memberships.user_id=1) as member", your answer doesn't answer my question at all.
A: 

I don't see why you would want to set boolean attributes via the SQL queries. You can do this with good ol' Ruby, which also lets you use has many through as jdl said.

class Book
  def member?
    user_id == 1
  end
end
August Lilleaas