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

时间:2016-09-05 15:44:08

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

为这样一个混乱的标题道歉,

我有2个型号:

User.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

我想显示特定用户的所有朋友的列表。

配置文件控制器:

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

2 个答案:

答案 0 :(得分:1)

您尝试在整个集合中调用列方法(访问数据库中列的值)。

由于每个用户都有很多朋友,user.friends会返回用户拥有的所有朋友的关联集合(即列表)。

所以current_user.friends.friend_id尝试在某种数组上调用friend_id,然后失败。您可以尝试map,但是......

这是一种更简单的方法! Rails可以为你做到:

def followed_users
   @friends = current_user.friends
end

但是,您需要HABTM关系(&#34;拥有并属于许多&#34;)。 Why is Access-Control-Expose-Headers needed?

class Friend < ApplicationRecord
 # nothing needed here
 # you need two keys in that table: user_id, friend_id
end
class User < ApplicationRecord
  has_many :friends, class_name: 'User', through: :friends # will pick with user_id
  has_many :befriended, class_name: 'User', through: :friends, foreign_key: 'friend_id' # To find who befriended that user.
end

答案 1 :(得分:1)

尝试以下

def followed_users
   @friends = User.where(id: current_user.friends.pluck(:friend_id))
end