1

Rails で初めて :​​through メソッドを使用しようとしており、豊富な多対多の関係の演習を行っています。テストしようとすると、コマンド ラインでエラーが発生しました。基本的に、「section_edits」を経由せずに AdminUser を「セクション」に向けようとしています。

ここにコンソールエラーがあります

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

関連する 3 つのクラスを次に示します。

AdminUser.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

Section.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 に答える