【问题标题】:Rails has many through errorRails 有很多错误
【发布时间】:2012-03-21 01:18:02
【问题描述】:

似乎我已经按照 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?

【问题讨论】:

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


    【解决方案1】:

    尝试更改 EditingSession 定义,使 belongs_to 标签为单数形式:

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

    但将 Document 和 Users 类中的其他源定义保留为复数形式(即 :source =&gt; :users:source =&gt; :documents

    这就是Ruby on Rails Has-Many-Through Guide 中的约定

    【讨论】:

    • 谢谢,这就是问题所在!这对我来说并不明显。我错过了什么逻辑?
    • 由于 Documents 类中的关联是“has_many”,rails 假定它应该是复数形式,这就是为什么它应该是 source=>:documents。但是,由于 EditingSession 使用的是“belongs_to”,它只能属于一个文档,因此 rails 假设应该有一个名为“:document”的字段。
    • 另外,在错误中,它显示“找不到源关联:文档”。整个约定需要一点时间来适应。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-30
    • 2021-04-08
    • 2012-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-24
    相关资源
    最近更新 更多