我有三个模型,在这里我们尝试创建一个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
答案 0 :(得分:3)
我不能确定问题是什么,但我可以指出一些事情:
UserCategory的accepts_nested_attributes_for,这是否意味着您希望能够动态创建类别?
类别has_many:用户,通过:: user_categories,而不是用户
您需要遵循Rails文件命名约定user.rb,user_category.rb和category.rb
这些可能不是问题/解决方案,但我相信它们会解决问题。