0

Rails have method where which returns Relation and find method which accepts entity and looks based on primary (you shouldn't specify it explicit).

Is there any where method which accepts entity?

eg, User.where(params[:id]) -> select .. from users where user.id = ...

tereško
  • 58,060
  • 25
  • 98
  • 150
Kirill Salykin
  • 681
  • 6
  • 19

2 Answers2

1

If you already have the user record, why do you need to find it again using where? If it's an association, you can do something like User.where(:company_id => company.id), but you can't pass the record itself.

Also,User.find(params[:id]) is the same as User.where(:id => params[:id]).first.

Josh Rieken
  • 2,256
  • 1
  • 19
  • 23
  • I meant this: Post.find(params[:id]) - will use id and look Post.primary_key == id, how can i do this using where method? – Kirill Salykin Jan 20 '13 at 22:57
  • id specified explicitly. find(params[:id]) uses primary key from mapping. Find will work with FriendlyId, but where wont. – Kirill Salykin Jan 20 '13 at 23:01
  • Why is your primary key something other than id? Rails doesn't like that. I'd recommend changing that back if you can to avoid tearing out your hair. See also, http://stackoverflow.com/questions/10079195/how-to-set-primary-key-in-ruby-on-rails-migration – Josh Rieken Jan 20 '13 at 23:04
  • I wanted https://github.com/norman/friendly_id to play with where. I thought the point is to change primary key, but i was mistaken, FriendlyId overrides finder methods. But thanks anyway! – Kirill Salykin Jan 20 '13 at 23:11
1

The following works, but I don't understand why you are looking for an object you already have?

User.where(:id => user)
Marcel Hebing
  • 3,072
  • 1
  • 19
  • 22