用户has_many关联不起作用(错误:找不到关联:模型类别中的user_categories)

时间:2016-06-09 20:00:56

标签: ruby-on-rails ruby ruby-on-rails-3 activerecord devise

我有三个模型,在这里我们尝试创建一个has_many。我基本上希望我的用户(使用设计)有很多类别。和类别有很多用户。

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&lt;&lt;用户我收到此错误:

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

1 个答案:

答案 0 :(得分:3)

我不能确定问题是什么,但我可以指出一些事情:

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

  2. 类别has_many:用户,通过:: user_categories,而不是用户

  3. 您需要遵循Rails文件命名约定user.rb,user_category.rb和category.rb

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