2013-07-19 9 views
7

मैं अनुवर्ती सिस्टम बनाने के लिए माइकल हार्टल ट्यूटोरियल का पालन कर रहा हूं लेकिन मुझे एक अजीब त्रुटि है: "अपरिभाषित विधि 'find_by' []: ActiveRecord: :रिश्ता"। मैं प्रमाणीकरण के लिए तैयार कर रहा हूँ।NoMethodError - अपरिभाषित विधि 'find_by' []: ActiveRecord :: Relation

मेरा विचार /users/show.html.erb कि तरह लग रहा है:

. 
. 
. 
<% if current_user.following?(@user) %> 
    <%= render 'unfollow' %> 
<% else %> 
    <%= render 'follow' %> 
<% end %> 

उपयोगकर्ता मॉडल 'मॉडल/user.rb':

class User < ActiveRecord::Base 
devise :database_authenticatable, :registerable, :recoverable, :rememberable,  :trackable, :validatable 

has_many :authentications 
has_many :relationships, foreign_key: "follower_id", dependent: :destroy 
has_many :followed_users, through: :relationships, source: :followed 
has_many :reverse_relationships, foreign_key: "followed_id", class_name: "Relationship", dependent: :destroy 
has_many :followers, through: :reverse_relationships, source: :follower 

    def following?(other_user) 
     relationships.find_by(followed_id: other_user.id) 
    end 

    def follow!(other_user) 
     relationships.create!(followed_id: other_user.id) 
    end 

    def unfollow!(other_user) 
     relationships.find_by(followed_id: other_user.id).destroy 
    end 

end 

रिश्ता मॉडल 'मॉडल/relationship.rb ':

class Relationship < ActiveRecord::Base 

    attr_accessible :followed_id, :follower_id 

    belongs_to :follower, class_name: "User" 
    belongs_to :followed, class_name: "User" 

    validates :follower_id, presence: true 
    validates :followed_id, presence: true 

end 

रेल कह रहा है कि इस मुद्दे को उपयोगकर्ता मॉडल में है: "relationships.find_by (followed_id: other_user.id)" क्योंकि मीटर थोड परिभाषित नहीं है, लेकिन मुझे समझ में नहीं आता क्यों?

उत्तर

22

मेरा मानना ​​है कि find_by रेल 4 में पेश किया गया था आप रेल 4 का उपयोग नहीं कर रहे हैं, तो where और first के संयोजन द्वारा find_by बदलें।

relationships.where(followed_id: other_user.id).first 

तुम भी उपयोग कर सकते हैं गतिशील find_by_attribute

relationships.find_by_followed_id(other_user.id) 
एएसआईडीई

:

मैं तुम्हें अपने following? पद्धति को बदलने के बजाय एक रिकॉर्ड की तुलना में एक truthy मान देने के लिए (या नहीं के बराबर है जब कोई रिकॉर्ड नहीं है का सुझाव मिल गया)। आप exists? का उपयोग कर ऐसा कर सकते हैं।

relationships.where(followed_id: other_user.id).exists? 

इसका एक बड़ा फायदा यह है कि यह कोई वस्तु नहीं बनाता है और केवल एक बूलियन मान देता है।

+0

कार्य का उपयोग कर सकते है, धन्यवाद! और आप बूलियन मूल्य के लिए सही हैं, यह बहुत बेहतर है। – titibouboul

2

आप

relationships.find_by_followed_id(other_user_id) 

या

relationships.find_all_by_followed_id(other_user_id).first 
संबंधित मुद्दे