Rails has_many错误

时间:2012-03-21 01:18:03

标签: ruby-on-rails activerecord associations ruby-on-rails-3.2

似乎我已将源定义为AR错误消息,但仍会出现错误。任何的想法? Rails 3.2,Ruby 1.9.2

    class Document < ActiveRecord::Base
      has_many :participations
      has_many :users, :through => :participations

      has_many :editing_sessions
      has_many :editors, :through => :editing_sessions, :source => :users
    end


    class User < ActiveRecord::Base
      has_many :participations
      has_many :documents , :through => :participations

      has_many :editing_sessions
      has_many :open_documents, :through => :editing_sessions, :source => :documents
    end


    class EditingSession < ActiveRecord::Base
      belongs_to :users
      belongs_to :documents
    end

    create_table "editing_sessions", :force => true do |t|
      t.integer  "user_id"
      t.integer  "document_id"

      t.datetime "created_at",  :null => false
      t.datetime "updated_at",  :null => false
    end


    Console:

    u = User.first
    => ... OK

    u.editing_sessions
    => []

    u.open_documents
    => ActiveRecord::HasManyThroughSourceAssociationNotFoundError: Could not find the source association(s) :document in model EditingSession. Try 'has_many :open_documents, :through => :editing_sessions, :source => <name>'. Is it one of :users or :documents?

1 个答案:

答案 0 :(得分:3)

尝试更改EditingSession定义,以便belongs_to标签采用单数形式:

class EditingSession < ActiveRecord::Base
  belongs_to :user
  belongs_to :document
end

但是将其他源定义保留在复数形式的Document和Users类中(即:source => :users:source => :documents

这是Ruby on Rails Has-Many-Through Guide

中的惯例