簡體   English   中英

Michael Hartl教程的第11章中的“未定義的方法'find_by'”

[英]“undefined method `find_by'” in Chapter 11 of Michael Hartl's tutorial

我遇到了這兩個錯誤,不確定如何解決。 我遇到的一個問題是本教程的新版本與舊版本之間的差異(rails 4和3.2之間的差異)。

我的規格是:

Ruby版本:1.9.2p320

Rails版本:3.2.13

R規格:2.11.1

電腦:Macbook Pro OS X Mountain Lion

失誤

  1) User following and unfollowing 
     Failure/Error: before { @user.unfollow!(other_user) }
     NoMethodError:
       undefined method `find_by' for []:ActiveRecord::Relation
     # ./app/models/user.rb:36:in `unfollow!'
     # ./spec/models/user_spec.rb:47:in `block (4 levels) in <top (required)>'

  2) User following and unfollowing followed_users 
     Failure/Error: before { @user.unfollow!(other_user) }
     NoMethodError:
       undefined method `find_by' for []:ActiveRecord::Relation
     # ./app/models/user.rb:36:in `unfollow!'
     # ./spec/models/user_spec.rb:47:in `block (4 levels) in <top (required)>'

User.rb

  def following?(other_user)
    relationships.where(followed_id: other_user.id).first
  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

user_spec.rb

describe "following" do
    let(:other_user) { FactoryGirl.create(:user) }
    before do
      @user.save
      @user.follow!(other_user)
    end

    it { should be_following(other_user) }
    its(:followed_users) { should include(other_user) }

    describe "followed users" do 
      subject { other_user }
      its(:followers) {should include(@user) } 
    end

    describe "and unfollowing" do
      before { @user.unfollow!(other_user) }

      it {should_not be_following(other_user) }
      its(:followed_users) {should_not include(other_user) }
    end
  end

在使用時, find_by在Rails 3中不存在find_by為此使用了method_missing ,因此可以使用find_by_followed_id

我建議使用Hartl的Rails 3教程

嘗試:

def unfollow!(other_user)
  relationships.find_by_followed_id(other_user.id).destroy!
end

作為參考,find_by_X方法已不推薦使用rails4。所有查詢現在都是Model.find(attribute:“ attribute”)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM