我收到了这2个错误,我不知道如何修复它们。我遇到的一个问题是新版教程和旧版本(rails 4和3.2之间的区别)之间的差异。
我的规格是:
Ruby版本:1.9.2p320
Rails版本: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)>'
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
答案 0 :(得分:2)
find_by
在Rails 3中不存在.Rails 3为此使用了method_missing
,因此使用find_by_followed_id
将起作用。
我建议使用Hartl的Rails 3 tutorial。
答案 1 :(得分:1)
尝试:
def unfollow!(other_user)
relationships.find_by_followed_id(other_user.id).destroy!
end
答案 2 :(得分:0)
作为FYI,使用rails 4不推荐使用find_by_X方法。所有查询现在都是Model.find(属性:“attribute”)