0

我收到这 2 个错误,但我不确定如何修复它们。我遇到的一个问题是本教程的新版本和旧版本之间的差异(rails 4 和 3.2 之间的差异)。

我的规格是:

红宝石版本:1.9.2p320

导轨版本:3.2.13

Rspec: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)>'

用户.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
4

3 回答 3

2

find_by当您使用它时,Rails 3 中不存在它。Rails 3 为此使用method_missing了它,因此使用find_by_followed_id会起作用。

我推荐使用 Hartl 的Rails 3 教程

于 2013-08-13T19:07:27.027 回答
1

尝试:

def unfollow!(other_user)
  relationships.find_by_followed_id(other_user.id).destroy!
end
于 2013-08-13T19:04:40.203 回答
0

作为一个仅供参考,find_by_X 方法已被 rails 4 弃用。所有查询现在都是 Model.find(attribute: "attribute")

于 2013-08-13T21:54:58.117 回答