bradpotts bradpotts - 6 months ago 19
Ruby Question

Getting Data from API (ok 200 Response Undefined Method 'id')

I got the below to work and call up membership data based on current_user.id (See 200 Ok response) this shows up in my logs.

GET https://api-e1.authrocket.com/v1/memberships?user_id=usr_0vKhXTr0K1bz6kUipKNnjD
-> 200 (103.4 ms)
NoMethodError (undefined method `id' for #<NCore::Collection:0x007f50c82a7e50>):app/controllers/directory/categories_controller.rb:13:in `index'


I was using current_user.id which worked.

@directory_category.user_id = current_user.id


Trying to change it so it grabs the user's membership.id

@directory_category.user_id = membership_info.id


The full create statement I'm working with.

# Create
def create
@directory_category = Directory::Category.new(directory_category_params)
@directory_category.user_id = membership_info.id
if @directory_category.save
redirect_to directory_categories_path, notice: 'Category was successfully created.'
else
render :new
end
end

# Directory Category Index
def index
@directory_categories = Directory::Category.where(user_id: membership_info.id)
end


My attempt, which does say 200 ok getting current_user id and putting it at the end AuthRocket::Membership.all statement like below:

def current_user
@_current_user ||= AuthRocket::Session.from_token(session[:ar_token]).try(:user)
end

def membership_info
AuthRocket::Membership.all user_id: current_user.id
end


https://authrocket.com/docs/api/memberships

Answer

It looks like your

def membership_info
    AuthRocket::Membership.all user_id: current_user.id
end

method is actually returning a collection and not a single item. if you change it to

def membership_info
    AuthRocket::Membership.all(user_id: current_user.id).first
end

or whichever record you actually want, you should stop this error from raising.