对如此令人困惑的标题表示歉意,
我有 2 个型号:
用户.rb
class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :friends
end
friend .rb
class Friend < ApplicationRecord
belongs_to :user
end
我想显示特定用户的所有好友列表。
配置文件 Controller :
class ProfilesController < ApplicationController
def show
end
def followed_users
@friends = User.where(id: current_user.friends.friend_id)
end
end
followed_users.html.erb
<% @friends.each do |f| %>
<%= f.email %>
<% end %>
但这不起作用,我收到以下错误:
NoMethodError in ProfilesController#followed_users
undefined method `friend_id' for # <Friend::ActiveRecord_Associations_CollectionProxy:0x007fb960747a90> Did you mean? find_index
最佳答案
尝试以下
def followed_users
@friends = User.where(id: current_user.friends.pluck(:friend_id))
end
关于ruby-on-rails - (Rails) 如何通过 id 查找用户并将用户保存到另一个具有用户 id 的模型中的实例中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39333948/