我一直在关注Michael Heartl教程来创建一个跟随系统,但我有一个奇怪的错误:“未定义的方法`find_by’为[]:ActiveRecord :: Relation”.我正在使用设计进行身份验证.
我的观点/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)”因为mthod没有定义,但我不明白为什么?
解决方法
我相信find_by是在rails 4中引入的.如果你没有使用rails 4,请将where_by替换为where和first.
relationships.where(followed_id: other_user.id).first
您还可以使用动态find_by_attribute
relationships.find_by_followed_id(other_user.id)
在旁边:
我建议你改变你的追随者?返回truthy值而不是记录的方法(或没有找到记录时为nil).你可以使用exists吗?
relationships.where(followed_id: other_user.id).exists?
这样做的一大优点是它不会创建任何对象,只返回一个布尔值.