【问题标题】:Has many :through association not found有很多:通过关联未找到
【发布时间】:2012-02-29 17:00:06
【问题描述】:

我有两个模型可以添加标签。

  • 播放器
  • 门票

我有一个属于两者的Tag 模型,所以我有两个连接模型

  • tag_ticket
  • 标签播放器

我收到 Could not find the association :tag_tickets in model Ticket 错误,但我的关联在其中。

class Ticket < ActiveRecord::Base
  has_many :tag_tickets
  has_many :tags, :through => :tag_tickets
end

我只关注Ticket 模型,但播放器模型应该看起来相似。

这是我对 TagTicket 的迁移

class CreateTagTickets < ActiveRecord::Migration
  def change
    create_table :tag_tickets do |t|
      t.integer :ticket_id
      t.integer :tag_id

      t.timestamps
    end
  end
end

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 has-many model-associations


    【解决方案1】:

    您需要先指定 :tag_tickets 加入,如下所示:

    class Ticket < ActiveRecord::Base
      has_many :tag_tickets
      has_many :tags, :through => :tag_tickets
    end
    

    您还需要在 TagTicket 模型中指定连接:

    class TagTicket < ActiveRecored::Base
      belongs_to :ticket
      belongs_to :tag
    end
    

    或者,您可以跳过所有这些并使用 habtm 连接(仅在 tag_tickets 连接真正用作连接并且本身没有主键时才推荐)。在这种情况下,您将没有 TagTicket 模型(只是一个 tag_tickets 表),Ticket 模型如下所示:

    class Ticket < ActiveRecord::Base
      has_and_belongs_to_many :tags
    end
    

    【讨论】:

    • 我之前尝试过顶级选项,但我得到了这个Could not find the source association(s) :tag or :tags in model TagTicket. Try 'has_many :tags, :through =&gt; :tag_tickets, :source =&gt; &lt;name&gt;'. Is it one of ?
    • 谢谢,中间部分有帮助。 rails 错误只抱怨Ticket 问题的一半:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-28
    • 2012-04-29
    • 1970-01-01
    • 1970-01-01
    • 2023-01-12
    相关资源
    最近更新 更多