ActiveRecord :: HasManyThroughAssociationNotFoundError按照文档的一切问题

时间:2018-01-23 05:43:19

标签: ruby-on-rails ruby activerecord associations

以下是我的模特:

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 个答案:

答案 0 :(得分:3)

  

至:: client_authorization_rule

应该是client_authorization_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

当你在rails 5中编写belongs_to :project时,另外还有一个注意事项,它自动意味着在保存之前需要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

答案 1 :(得分:3)

关注

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