ruby on rails - Can't use `find_by` method while `where` works in ActiveRecord::Base -
ruby on rails - Can't use `find_by` method while `where` works in ActiveRecord::Base -
i have method this, 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 changed where(...).first
find_by
, because thought 2 look 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 undefined method `find_by' #<class:0x007fbb2b674970>
error when seek create user
.
i have no thought why find_by
doesn't work here. i'll grateful if tell me wrong.
find_by
method introduced in rails 4. if you're using rails 3.x or lesser version use: find_by_<attribute_name>
instead:
find_by_twitter_id(twitter_id)
but, there's method find , create attributes passed it, can utilize if fits needs:
find_or_create_by_twitter_id(twitter_id)
ruby-on-rails activerecord
Comments
Post a Comment