Gugubaight Gugubaight - 2 months ago 5
Ruby Question

Rails 4 Error: NoMethodError - undefined method `itemfavorites'

Hey I am receiving an issue when accessing

@interestedusers = User.itemfavorites.where(item_id: @item.id)
from my
ItemsController
:

NoMethodError in ItemsController#show
undefined method `itemfavorites' for #<Class:0xfb94bb8>


Routes

resources :items do
get :itemfavorites, on: :member
end


User Model

# Favorite items of user
has_many :favorite_items # just the 'relationships'
has_many :itemfavorites, through: :favorite_item, source: :item # the actual items the user favorites


Item Model

# Favorited by users
has_many :favorite_items # just the 'relationships'
has_many :itemsfavorited_by, through: :favorite_items, source: :user # the actual users favoriting an item


The general association works, I tested it and I can add/remove and display favorites.


I am trying to display the users favorited an Item.

Thanks in advance for each answer! Please tell me if you need additional information.

Answer

You are calling itemfavorites on the User class, not a User instance. I guess you want to do something like

@interestedusers = current_user.itemfavorites.where(item_id: @item.id)

or

@interestedusers = @user.itemfavorites.where(item_id: @item.id)

EDIT: you want to do this to get users for an item:

@interestedusers = @item.itemsfavorited_by
Comments