Грешка в Rails 4: ActiveRecord::HasManyThroughSourceAssociationNotFoundError


Хей,
това е разочароващо. Знам какво не е наред тук, но нямам решение да го поправя.

Първо грешката, подкана при щракване върху „Любими“ (/app/views/users/index.html.haml)

ActiveRecord::HasManyThroughSourceAssociationNotFoundError in UsersController#userfavorite

Could not find the source association(s) "userfavorite" or :userfavorites in model FavoriteUser. Try 'has_many :userfavorites, :through => :favorite_users, :source => <name>'. Is it one of c_user_id or user_id?

Заявка: Параметри:

{"_method"=>"get",
 "authenticity_token"=>"VkZF4RtOBSXLFw8mygor24Ty/Efx5uSWxto4qRWf1szu3YwFe1/F5+7QtEXXZv9eaQEQvM5O8ELX95wmPLdZYQ==",
 "type"=>"favorite", # What i am doing
 "id"=>"1"} # My user id

Моята цел е да позволя на потребителите (от потребителския модел) да предпочитат други потребители (потребителски модел) чрез любимия потребителски модел. Конфликтът тук: не мога да направя асоциациите правилно, защото имам само един модел, от който идват данните.

Нека ви покажа кода много бързо! (Конфликти user.rb)

app/models/favorite_user.rb

class FavoriteUser < ActiveRecord::Base
    belongs_to :c_user_id
    belongs_to :user_id
end

app/models/user.rb

class User < ActiveRecord::Base

  # Include default devise modules. Others available are:

  # :confirmable, :lockable, :timeoutable and :omniauthable

  devise :database_authenticatable, :registerable,
       :recoverable, :rememberable, :trackable, :validatable


  has_many :tools

  # Favorite tools of user
  has_many :favorite_tools # just the 'relationships'
  has_many :favorites, through: :favorite_tools, source: :tool # the actual tools the user favorites

  # Favorite users of user
  has_many :favorite_users # just the 'relationships'
  has_many :userfavorites, through: :favorite_users, source: :user # conflicting! Can't link to userscontroller cause it belongs to the user model, the model we are at right now.
  has_many :userfavorited_by, through: :favourite_users, source: :user # conflicting! Can't link to userscontroller cause it belongs to the user model, the model we are at right now.



  mount_uploader :avatar_filename, AvatarUploader

end

app/controllers/users_controller.rb

class UsersController < ApplicationController
    before_action :find_user, only: [:show, :favorite]

    # Add and remove favorite recipes
    # for current_user
    def userfavorite
      type = params[:type]
      if type == "favorite"
        current_user.userfavorites << @user
        redirect_to :back

      elsif type == "unfavorite"
        current_user.userfavorites.delete(@user)
        redirect_to :back    
      else
        # Type missing, nothing happens
        redirect_to :back, notice: 'Nothing happened.'
      end
    end

    def index
        @users = User.all
    end

    def show
        @tools = Tool.where(user_id: @user).order("created_at DESC")
        @tool = Tool.find(1)
    end

    private

    def find_user
        @user = User.find(params[:id])
    end
end

app/views/users/index.html.haml

- @users.each do |user|
    = image_tag gravatar_for user if user.use_gravatar == true
    = image_tag user.avatar_filename.url if user.use_gravatar == false
    %h2= link_to user.username, user
    %p= link_to "Favorite", favorite_user_path(user, type: "favorite"), method: :get
    %p= link_to "Unfavorite", favorite_user_path(user, type: "unfavorite"), method: :get

app/config/routes.rb

resources :users, only: [:index, :show, :userfavorite] do 
    get :userfavorite, on: :member
end

Атрибути на :favorite_users

c_user_id:integer user_id:integer

(=> c_user_id за текущия потребителски идентификатор - така че потребителят, който добавя любими потребители)


Надявам се, че предоставените данни са достатъчни, ако не, моля, кажете ми. Благодарен съм за всички ваши отговори.


person Gugubaight    schedule 05.09.2016    source източник
comment
какви са атрибутите за :favorite_users модел?   -  person mrvncaragay    schedule 05.09.2016
comment
@mrvncaragay c_user_id:integer user_id:integer (=› c_user_id за текущия потребителски идентификатор - така че потребителят, който добавя любими потребители)   -  person Gugubaight    schedule 05.09.2016
comment
не сте настроили връзките си правилно, напр. Foreign_key. ще напиша моето предложение   -  person mrvncaragay    schedule 05.09.2016


Отговори (1)


Ето моето предложение:

user.rb

userfavorites - ще покаже всички потребители, които сте означили като любими

has_many :favorite_relationships, class_name: "FavoriteUser", foreign_key: "c_user_id"
has_many :userfavorites, through: :favorite_relationships, source: :user

userfavorited_by - ще изброи всички потребители, които са ви означили като любими

has_many :favorited_relationships, class_name: "FavoriteUser", foreign_key: "user_id"
has_many :userfavorited_by, through: :favorited_relationships, source: :c_user

Любим потребител

редактирано:

class FavoriteUser < ActiveRecord::Base
    belongs_to :c_user, class_name: "User"
    belongs_to :user, class_name: "User"
end

След като направите промени, уверете се, че test първо във вашия console дали връзките работят. след това направете подходяща промяна във вашия изглед, контролер и т.н...

person mrvncaragay    schedule 05.09.2016
comment
Оценявам отговора ви, звучи добре. Но когато се опитам, че chrome извежда нещо, което е доста странно, защото му липсва „do“ в класа FavoriteUser c:/Users/Jonas/gitapps/ocubit/app/models/favorite_user.rb:2: синтактична грешка, неочаквано tSTRING_BEG, очаквам keyword_do или '{' или '(' belongs_to :c_user_id, class_name User ^ c:/Users/Jonas/gitapps/ocubit/app/models/favorite_user.rb:3: синтактична грешка, неочакван tSTRING_BEG, очаквам keyword_do или '{' или '(' принадлежи_на :user_id, class_name потребител ^ - person Gugubaight; 05.09.2016
comment
Не "направи", а някои други неща, които обикновено не са в час - person Gugubaight; 05.09.2016
comment
да, това е странно. гледам кода, който публикувах, и не виждам никаква синтактична грешка. тествахте ли го в конзолата си? - person mrvncaragay; 05.09.2016
comment
Това е, което прави в конзолата (същата грешка): irb(main):002:0› User.find(1).userfavorites ‹‹ @c_user_id.find(1) Потребителско натоварване (0.0ms) ИЗБЕРЕТЕ потребители.* ОТ потребители WHERE users.id =? ОГРАНИЧЕНИЕ 1 [[id, 1]] - person Gugubaight; 05.09.2016
comment
SyntaxError: c:/Users/Jonas/gitapps/ocubit/app/models/favorite_user.rb:2: синтактична грешка, неочакван tSYMBEG, очаква се keyword_do или '{' или '(' {belongs_to :c_user_id, class_name User} ^ c: /Users/Jonas/gitapps/ocubit/app/models/favorite_user.rb:2: синтактична грешка, неочаквано '}', очакване на keyword_end c:/Users/Jonas/gitapps/ocubit/app/models/favorite_user.rb:3: синтактична грешка, неочакван '}', очакване на keyword_end от - person Gugubaight; 05.09.2016
comment
имате ли този проект качен в github? - person mrvncaragay; 05.09.2016
comment
все още не, това ще помогне ли или имате нужда от конкретни файлове или скъпоценните камъни, които съм инсталирал? - person Gugubaight; 05.09.2016
comment
всичко е наред. просто ще пресъздам вашите модели на моята локална машина и ще го тествам и ще видя дали работи. - person mrvncaragay; 05.09.2016
comment
току-що актуализира моите малки промени. тествах го и работи според очакванията - person mrvncaragay; 05.09.2016
comment
забравил си запетая в редактирания си отговор. Ще се опитам да продължа да решавам проблемите си, когато се прибера по-късно - person Gugubaight; 06.09.2016
comment
ааа... Поправих синтактичната грешка. Също така липсва двоеточие след 'class_name' и на двата реда. Сега получавам шаблон, който липсва, тогава ще го изтрия - person Gugubaight; 06.09.2016
comment
Да направи промяната. - person mrvncaragay; 06.09.2016
comment
Мисля, че успях. Знаете ли как да насочите любимите потребители на потребител на /app/views/users/index.html.haml? - person Gugubaight; 06.09.2016
comment
Да, просто направете още една публикация по този въпрос. - person mrvncaragay; 06.09.2016
comment
stackoverflow.com/questions/39353525 / - person Gugubaight; 06.09.2016