User has_many association not working (error:Could not find the association :user_categories in model Category)
User has_many association not working (error:Could not find the association :user_categories in model Category)
我有三个模型,当我尝试创建一个 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 << 用户我得到这个错误:
ActiveRecord::HasManyThroughAssociationNotFoundError: 在模型类别
中找不到关联:user_categories
我不能确定问题出在哪里,但我可以指出几点:
UserCategory 的 accepts_nested_attributes_for,这是否意味着您希望能够动态创建类别?
类别has_many:用户,通过::user_categories,不是用户
您需要遵循 Rails 文件命名约定,user.rb、user_category.rb 和 category.rb
这些可能不是 problem/solution,但我相信它们是解决问题的方法。
我有三个模型,当我尝试创建一个 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 << 用户我得到这个错误:
ActiveRecord::HasManyThroughAssociationNotFoundError: 在模型类别
中找不到关联:user_categories我不能确定问题出在哪里,但我可以指出几点:
UserCategory 的 accepts_nested_attributes_for,这是否意味着您希望能够动态创建类别?
类别has_many:用户,通过::user_categories,不是用户
您需要遵循 Rails 文件命名约定,user.rb、user_category.rb 和 category.rb
这些可能不是 problem/solution,但我相信它们是解决问题的方法。