nharvey27
nharvey27

Reputation: 11

Querying foreing_key on a belongs_to association. Rails

I am having trouble implementing a bookmark feature. I want to query all the techniques in the bookmark table matching the current user's id. The problem is I can't get the query to pull out the attributes of the actuall technique. I keep getting method "uid" missing

This is the controller with the query

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

The Bookmark model

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

The User Model

class User < ActiveRecord::Base
has_many :bookmarks
end

I am sure their is a problem with my query but I'm stuck.

Upvotes: 0

Views: 26

Answers (2)

gnerkus
gnerkus

Reputation: 12047

The query throws an error because the current_user is not of the right type required in the where clause. You need to specify the current user's id. Also, your query would result in a collection of :bookmarks and not techniques.

A solution to this would be to execute the joins query and obtain the matched collection of techniques:

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

Upvotes: 0

Dharam Gollapudi
Dharam Gollapudi

Reputation: 6438

When you do Bookmark.joins(:technique).where(user_id: current_user), you get a collection of bookmarks, not techniques.

If you want the techniques, you could do the following:

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

Upvotes: 1

Related Questions