我有两个模型通过关联加入了has_many:
以下是表格:
create_table "organizations", force: :cascade do |t|
t.string "name"
t.string "description"
t.string "mission"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "organizations_users", force: :cascade do |t|
t.integer "user_id"
t.integer "organization_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "first_name"
t.string "last_name"
end
以下是模型:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :organizationsusers
has_many :organizations, :through => :organizationsusers
end
class Organization < ActiveRecord::Base
has_many :organizationsusers
has_many :users, :through => :organizationsusers
has_many :categories, as: :categorizable
end
class OrganizationsUser < ActiveRecord::Base
belongs_to :user
belongs_to :organization
end
当我通过表单创建新组织时,它会充分创建。但是我一直得到:
NameError: uninitialized constant Organization::Organizationsuser
如果我做这样的事情,例如:
o = Organization.last
Organization Load (0.4ms) SELECT "organizations".* FROM "organizations" ORDER BY "organizations"."id" DESC LIMIT 1
=> #<Organization id: 1, name: "HOU", description: "fkjndskj", mission: "fnskjdfs", created_at: "2015-09-16 07:35:42", updated_at: "2015-09-16 07:35:42">
o.users
NameError: uninitialized constant Organization::Organizationsuser
为什么会这样?我在这里误解了什么吗?
答案 0 :(得分:4)
NameError:未初始化的常量Organization :: Organizationsuser
将代码中的organizationsusers
更改为organizations_users
可以解决错误。
#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
has_many :organizations_users
has_many :organizations, :through => :organizations_users
end
#organization.rb
class Organization < ActiveRecord::Base
has_many :organizations_users
has_many :users, :through => :organizations_users
has_many :categories, as: :categorizable
end
答案 1 :(得分:0)
我已经读过您的代码了。你有拼写错误来写你的联想。
请将:organizationsusers
更改为:organizations_users
。我希望这能帮到你