9

Michael Heartl のチュートリアルに従ってフォロー システムを作成しましたが、「[]:ActiveRecord::Relation の未定義メソッド `find_by'」という奇妙なエラーが発生しました。認証にdeviseを使用しています。

私のビュー /users/show.html.erb は次のようになります。

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

ユーザーモデル「models/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

リレーションシップ モデル 'models/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)" は、メソッドが定義されていないためですが、理由がわかりません。

4

2 に答える 2

25

Rails 4 で導入されたと思いfind_byます。Rails 4 を使用していない場合は、とfind_byの組み合わせに置き換えてください。wherefirst

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

ダイナミックも使えますfind_by_attribute

relationships.find_by_followed_id(other_user.id)

余談:

following?レコード (またはレコードが見つからない場合は nil) ではなく、真の値を返すようにメソッドを変更することをお勧めします。を使用してこれを行うことができますexists?

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

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

于 2013-07-19T16:08:51.783 に答える
3

使用できます

relationships.find_by_followed_id( other_user_id ) 

また

relationships.find_all_by_followed_id( other_user_id ).first
于 2013-10-03T02:35:15.717 に答える