ruby-on-rails - (Rails) 如何通过 id 查找用户并将用户保存到另一个具有用户 id 的模型中的实例中?

标签 ruby-on-rails ruby model-view-controller

对如此令人困惑的标题表示歉意,

我有 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/

相关文章:

ruby-on-rails - Rails 中八卦搜索的迁移

javascript - 在 Node.js 中的 Controller 中引用 Sequelize 模型

javascript - 使用 bootstrap3 modal、jquery 和 Rails 4 为我当前的模型创建父对象

ruby-on-rails - ruby/2.3.0/rubygems/core_ext/kernel_require.rb :55:in `require' : cannot load such file -- selenium-webdriver (LoadError)

mysql - 如何有效地将大量数据存储在DB中?

ruby - 创建 ruby gem

php - Zend Framework 2 - 在 View 中调用操作

ios - 在 View Controller 之间传递数据

ruby-on-rails - 类中的实例变量未保存

javascript - 有什么方法可以在 ruby​​ on Rails 应用程序中验证 JS 上电子邮件的唯一性吗?