Khoj Badami
Khoj Badami

Reputation: 191

ActiveRecord::HasManyThroughAssociationNotFoundError issue with everything as per the Docs

Below are my models:

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

So, I have followed everything as per the docs: http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

The errors I am getting is when I do something like:

p.clients

Here "p" is a project. I cannot even access the "clients" method on the project without getting the following error:

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

Not sure what I am missing. Thanks. My Rails version is Rails 5.0.6 and ruby 2.2.3. Is this some known issue? I cant find any one with this issue.

Upvotes: 0

Views: 75

Answers (2)

Anand
Anand

Reputation: 6531

through: :client_authorization_rule

it should be 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

one more thing as a side note when you write belongs_to :project in rails 5 it automatically means thats project_id is required before save. so there is no sense of 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

Upvotes: 3

Salil
Salil

Reputation: 47482

Following

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

Should be

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

Note :- through: :client_authorization_rule should be through: :client_authorization_rules

Upvotes: 3

Related Questions