代码之家  ›  专栏  ›  技术社区  ›  Khoj Badami

ActiveRecord::根据文档,所有内容都存在许多ThroughAssociationNotFoundError问题

  •  0
  • Khoj Badami  · 技术社区  · 6 年前

    以下是我的型号:

    class Client < ApplicationRecord
    
      has_many :client_authorization_rules
      has_many :projects, through: :client_authorization_rule
    
    end
    
    class Project < ApplicationRecord
    
      has_many :client_authorization_rules
      has_many :clients, through: :client_authorization_rule
    
    end
    
    class ClientAuthorizationRule < ApplicationRecord
    
      belongs_to :project
      belongs_to :client
    
      validates_presence_of :project
      validates_presence_of :client
    
    end
    

    因此,我按照文件的要求遵守了所有规定: http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

    我犯的错误是当我做以下事情时:

    p.clients
    

    这里的“p”是一个项目。我甚至无法访问项目上的“clients”方法,否则会出现以下错误:

    ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association :client_authorization_rule in model Project
    

    不知道我错过了什么。谢谢我的Rails版本是Rails 5.0.6和ruby 2.2.3。这是已知的问题吗?我找不到有这个问题的人。

    2 回复  |  直到 6 年前
        1
  •  3
  •   Anand    6 年前

    通过::client\u authorization\u rule

    应该是client\u authorization\u rules

    class Client < ApplicationRecord
    
      has_many :client_authorization_rules
      has_many :projects, through: :client_authorization_rules
    
    end
    
    class Project < ApplicationRecord
    
      has_many :client_authorization_rules
      has_many :clients, through: :client_authorization_rules
    
    end
    

    还有一件事作为你写作时的旁注 belongs_to :project 在rails 5中,它自动表示 project_id 保存前需要。所以没有意识到 validates_presence_of :project

    class ClientAuthorizationRule < ApplicationRecord
    
      belongs_to :project #it means that project_id required is true
      belongs_to :client  #it means that client_id required is true
    
      #validates_presence_of :project
      #validates_presence_of :client
    
    end
    
        2
  •  3
  •   Salil    6 年前

    下列的

    class Client < ApplicationRecord
    
      has_many :client_authorization_rules
      has_many :projects, through: :client_authorization_rule
    
    end
    
    class Project < ApplicationRecord
    
      has_many :client_authorization_rules
      has_many :clients, through: :client_authorization_rule
    
    end
    

    应该是

    class Client < ApplicationRecord    
      has_many :client_authorization_rules
      has_many :projects, through: :client_authorization_rules    
    end
    
    class Project < ApplicationRecord    
      has_many :client_authorization_rules
      has_many :clients, through: :client_authorization_rules    
    end
    

    注:- through: :client_authorization_rule 应该是 through: :client_authorization_rules