Reputation: 15141
I have a method like this, that works fine.
class User < ActiveRecord::Base
def self.find_or_create_from_twitter_id(twitter_id)
user = where(twitter_id: twitter_id).first
user ||= create_from_twitter_id(twitter_id)
end
end
Then I changed where(...).first
to find_by
, because I thought the two expression are basically same.
def self.find_or_create_from_twitter_id(twitter_id)
user = find_by(twitter_id: twitter_id)
user ||= create_from_twitter_id(twitter_id)
end
But I get undefined method `find_by' for #<Class:0x007fbb2b674970>
error when I try to create a User
.
I have no idea why find_by
doesn't work here. I'll be very grateful if you tell me what is wrong.
Upvotes: 0
Views: 53
Reputation: 15992
find_by
method is introduced in Rails 4. If you're using Rails 3.x or lesser version then use: find_by_<attribute_name>
instead:
find_by_twitter_id(twitter_id)
But, then there's another method which find and create by the attributes passed to it, which you can use if it fits your needs:
find_or_create_by_twitter_id(twitter_id)
Upvotes: 2