简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM