2016-06-09 50 views
1

我有三个模型,在这里他们是当我尝试创建has_many时。我基本上希望我的用户(使用设计)有很多类别。和类别有很多用户。用户has_many协会不工作(错误:无法找到关联:model_type中的user_categories)

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, 
     :omniauthable 

    has_many :user_categories 
    has_many :categories, through: :user_categories 


    acts_as_messageable 

    def mailboxer_email(object) 
    email 
    end 
end 

userCategory.rb

class UserCategory < ActiveRecord::Base 

    belongs_to :user 
    belongs_to :category 

    accepts_nested_attributes_for :categories 

end 

Category.rb

class Category < ActiveRecord::Base 

    has_many :user_categories 
    has_many :user, through: :user_categories 

    validates :name, presence: true, length: {minimum: 3, maximum: 25} 
    validates_uniqueness_of :name 
end 

当我运行category.users < <用户我得到这个错误:

的ActiveRecord :: HasManyThroughAssociationNotFoundError:找不到关联:user_categories模型类别

回答

3

我不能肯定地说这个问题可能是什么,但几件事情我可以指出:

  1. UserCategory的accepted_nested_attributes_for,这是否意味着您希望能够动态创建类别?

  2. 类别的has_many:用户,通过:user_categories,没有用户

  3. 您需要按照Rails的文件命名约定,user.rb,user_category.rb和category.rb

这些可能不是问题/解决方案,但我相信它们正在解决问题。