0

Ok so i have users and company and there a a join table on a many to many relationship

SO i can do

@user.companies

Can i do a scope that passes back the first company

i tied this in the user model

 scope :first_company, includes(:companies_users).where(:user_id => self.id).first

and this fails....any suggestions

Update

I have this that will work also but i was wondering if there was a equivalent scope

 def company
   self.companies.first
 end
Matt Elhotiby
  • 43,028
  • 85
  • 218
  • 321
  • `User` already has the method `first`. Use another name for your scope. – jdoe May 18 '12 at 13:26
  • sorry that was just an example...changing – Matt Elhotiby May 18 '12 at 13:29
  • Scope works on the whole model. Like `User.admins`. You're trying to make some "scope" on the `@user`, which obviously makes no sense: scope limits results, what can you limit on the `@user`? So, you're right when you create method, which is called on a particular user rather than on all users. – jdoe May 18 '12 at 13:37

1 Answers1

1

You need to define your scope as a lambda as the context of self in a scope would be the class not the instance.

see this SO article for how to do that.

Ruby Lambda and Scope

Community
  • 1
  • 1
engineerDave
  • 3,887
  • 26
  • 28