1

我第一次尝试在 rails 中使用 :through 方法,进行丰富的多对多关系练习,并在尝试对其进行测试时在命令行收到错误。基本上试图将 AdminUser 指向“sections”而不通过“section_edits”。

这是控制台错误

C:\Users\davo\Desktop\RailsProjects\simple_cms>rails c
Loading development environment (Rails 3.2.3)
irb(main):001:0> me = AdminUser.find(1)
  ←[1m←[36mAdminUser Load (1.0ms)←[0m  ←[1mSELECT `admin_users`.* FROM `admin_us
ers` WHERE `admin_users`.`id` = 1 LIMIT 1←[0m
=> #<AdminUser id: 1, first_name: "David", last_name: "Douglas", email: "", pass
word: nil, created_at: "2012-05-18 20:18:20", updated_at: "2012-05-18 20:18:20",
 username: "ddd1600">
irb(main):002:0> me.sections
ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the associa
tion "section_edits" in model AdminUser
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/activerecord-3.2.3/lib/active_r
ecord/reflection.rb:501:in `check_validity!'
        from C:/Ruby193/lib/ruby/gems/1.9.1/gems/activerecord-3.2.3/lib/active_r
#etc, etc

以下是三个相关的类:

管理员用户.rb

 class AdminUser < ActiveRecord::Base

  has_and_belongs_to_many :pages
  scope :named, lambda {|first,last| where(:first_name => first, :last_name => last)}

 has_many :section_edits
 has_many :sections, :through => "section_edits"
end

SectionEdit.rb

class SectionEdit < ActiveRecord::Base

  belongs_to :admin_user
  belongs_to :editor, :class_name => "AdminUser", :foreign_key => 'admin_user_id'

  belongs_to :section

end

节.rb

class Section < ActiveRecord::Base

  belongs_to :page
  has_many :section_edits

  has_many :admin_users, :through => :section_edits
  has_many :editors, :through => :section_edits, :class_name => "AdminUser"

end

编辑:我已经能够对 me.sections 执行(有点)反向命令而没有问题。下面,部分指向 AdminUser(编辑器)。

irb(main):003:0> section = Section.find(1)
  ←[1m←[35mSection Load (0.0ms)←[0m  SELECT `sections`.* FROM `sections` WHERE `
sections`.`id` = 1 LIMIT 1
=> #<Section id: 1, page_id: nil, name: "Section One", position: 1, visible: fal
se, content_type: nil, content: nil, created_at: "2012-05-18 22:50:44", updated_
at: "2012-05-18 22:50:44">
irb(main):004:0> section.editors
  ←[1m←[36mAdminUser Load (209.0ms)←[0m  ←[1mSELECT `admin_users`.* FROM `admin_
users` INNER JOIN `section_edits` ON `admin_users`.`id` = `section_edits`.`admin
_user_id` WHERE `section_edits`.`section_id` = 1←[0m
=> [#<AdminUser id: 1, first_name: "David", last_name: "Douglas", email: "", pas
sword: nil, created_at: "2012-05-18 20:18:20", updated_at: "2012-05-18 20:18:20"
, username: "ddd1600">]
irb(main):005:0>
4

1 回答 1

1

尝试改变:

 has_many :sections, :through => "section_edits"

到:

 has_many :sections, :through => :section_edits
于 2012-05-18T23:58:00.703 回答