我不确定为什么这个方法
Friendship.find_by_user_id_and_friend_id(user, friend)
&Friendship.find_by_user_id_and_friend_id(friend, user)
给出一个零, 能不能向我解释一下为什么方法
Friendship.find_by_user_id_and_friend_id(user, friend)
给出了nil和方法Friendship.find_by_user_id_and_friend_id(user.id, friend.id)
不?基本上可以解释一下给我的区别
2.3.0 :065 > user
=> #<User id: 1, email: "richill@gmail.com", created_at: "2016-11-22 15:56:19", updated_at: "2016-12-06 11:39:29", firstname: "richill", lastname: "artloe">
2.3.0 :068 > friend
=> #<User id: 2, email: "emma@gmail.com", created_at: "2016-11-22 16:19:25", updated_at: "2016-11-22 16:19:25", firstname: "emma", lastname: "watson">
Friendship.create(user: user, friend: friend, status: 'pending')
Friendship.create(user: friend, friend: user, status: 'requested')
2.3.0 :078 > Friendship.find_by_user_id_and_friend_id(user, friend)
Friendship Load (0.2ms) SELECT "friendships".* FROM "friendships" WHERE "friendships"."user_id" = ? AND "friendships"."friend_id" = ? LIMIT ? [["user_id", nil], ["friend_id", nil], ["LIMIT", 1]]
=> nil
2.3.0 :079 >
2.3.0 :079 > Friendship.find_by_user_id_and_friend_id(friend, user)
Friendship Load (0.2ms) SELECT "friendships".* FROM "friendships" WHERE "friendships"."user_id" = ? AND "friendships"."friend_id" = ? LIMIT ? [["user_id", nil], ["friend_id", nil], ["LIMIT", 1]]
=> nil
2.3.0 :080 >
我相信我想得到类似下面的结果:
>> Friendship.find_by_user_id_and_friend_id(user, friend)
=> #<Friendship:0x2bf74ec @attributes={"status"=>"pending", "accepted_at"=>nil,
"id"=>"1", "user_id"=>"1", "position"=>nil, "created_at"=>"2007-01-03 18:34:09",
"friend_id"=>"1198"}>
>> Friendship.find_by_user_id_and_friend_id(friend, user)
=> #<Friendship:0x490a7a0 @attributes={"status"=>"requested", "accepted_at"=>nil
, "id"=>"2", "user_id"=>"1198", "position"=>nil, "created_at"=>"2007-01-03 18:34
:20", "friend_id"=>"1"}>
很奇怪。它像这样放置
Friendship.find_by_user_id_and_friend_id(user.id, friend.id)
=> #<Friendship id: 1, user_id: 1, friend_id: 2, status: "pending", created_at: "2016-12-06 11:55:06", updated_at: "2016-12-06 11:55:06">
但是当这样放置时不起作用:
Friendship.find_by_user_id_and_friend_id(user, friend)
=> nil
可以解释为什么这对我来说
有什么区别
2.3.0 :016 > Friendship.find_by_user_id_and_friend_id(user, friend)
Friendship Load (0.2ms) SELECT "friendships".* FROM "friendships" WHERE "friendships"."user_id" = ? AND "friendships"."friend_id" = ? LIMIT ? [["user_id", nil], ["friend_id", nil], ["LIMIT", 1]]
=> nil
2.3.0 :017 > Friendship.find_by_user_id_and_friend_id(user.id, friend.id)
Friendship Load (0.2ms) SELECT "friendships".* FROM "friendships" WHERE "friendships"."user_id" = ? AND "friendships"."friend_id" = ? LIMIT ? [["user_id", 1], ["friend_id", 2], ["LIMIT", 1]]
=> #<Friendship id: 1, user_id: 1, friend_id: 2, status: "pending", created_at: "2016-12-06 11:55:06", updated_at: "2016-12-06 11:55:06">
2.3.0 :018 >
答案 0 :(得分:1)
find_by_id方法与使用where方法相同,只是它只返回找到的第一条记录。 (See the source code)
由于该方法正在搜索id,我相信您需要直接传递id而不是对象的实例才能使其工作。使用.find方法时也是如此。