查询belongs_to关联中的foreing_key。轨道

时间:2016-03-28 21:56:16

标签: ruby-on-rails ruby activerecord

我无法实现书签功能。我想查询与当前用户的id匹配的书签表中的所有技术。问题是我无法通过查询来获取实际技术的属性。我一直在想方法“uid”缺失

这是带有查询的控制器

def index 
 @technique = Bookmark.joins(:technique).where(user_id: current_user)
end

书签模型

class Bookmark < ActiveRecord::Base
 belongs_to :user
 belongs_to :technique
end

用户模型

class User < ActiveRecord::Base
has_many :bookmarks
end

我确信他们的查询存在问题,但我被困住了。

2 个答案:

答案 0 :(得分:1)

当您执行Bookmark.joins(:technique).where(user_id: current_user)时,您会收到bookmarks的集合,而不是techniques

如果您想要techniques,可以执行以下操作:

Bookmark.joins(:technique).where(user_id: current_user.id).collect(&:technique)

答案 1 :(得分:0)

查询引发错误,因为current_user不是where子句中所需的正确类型。您需要指定当前用户的ID。此外,您的查询会产生:bookmarks而非techniques的集合。

对此的解决方案是执行joins查询并获取匹配的技术集合:

def index 
 @technique = Bookmark.joins(:technique).where(user_id: current_user.id).collect(&:technique)
end
相关问题