2013-07-19 20 views
7

マイケル・ハートルのチュートリアルに従ってフォロー・システムを作成しましたが、奇妙なエラーがあります:[未定義メソッド `find_by for []:ActiveRecord: :関係"。私は認証のためにdeviseを使用しています。NoMethodError - 未定義のメソッド 'find_by for []: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 

Railsは問題がユーザーモデルであることを私に語っている: "relationships.find_by(followed_id:other_user.id)" をメートルので、 thodは定義されていませんが、なぜわかりませんか?

答えて

22

レール4にはfind_byが導入されていると思います。find_bywherefirstの組み合わせで置き換えてください。

レコードがないとき、私はあなたがtruthy値ではなく、レコード(またはnilを返すために、あなたのfollowing?方法を変更する提案:あなたはまた、ダイナミックfind_by_attribute

relationships.find_by_followed_id(other_user.id) 

を使用することができます

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

見つけた)。 exists?を使用してこれを行うことができます。

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

大きな利点の1つは、オブジェクトを作成せずにブール値を返すことです。

+0

ワーキングを使用することができ、感謝!そして、あなたはブール値のために正しいです、それははるかに良いです。 – titibouboul

2

あなたは

relationships.find_by_followed_id(other_user_id) 

または

relationships.find_all_by_followed_id(other_user_id).first 
関連する問題