【问题标题】:User has_many association not working (error:Could not find the association :user_categories in model Category)用户 has_many 关联不起作用(错误:在模型类别中找不到关联:user_categories)
【发布时间】:2016-06-09 20:00:56
【问题描述】:

我有三个模型,当我尝试创建一个 has_many 时它们就在这里。我基本上希望我的用户(使用设计)有很多类别。并且类别拥有许多用户。

用户.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

类别.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

【问题讨论】:

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


    【解决方案1】:

    我不能确定问题出在哪里,但我可以指出几点:

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

    2. 类别 has_many :users, through: :user_categories, not user

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-25
      • 2013-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多