【问题标题】:Association through another table "Unknown key: through"(Rails)通过另一个表关联“未知键:通过”(Rails)
【发布时间】:2012-10-06 21:15:01
【问题描述】:

我正在我的 rails 应用程序中创建旅行,我想为这些旅行添加类别。类别存储在我的数据库中的类别表中,用户可以选择适合旅行的类别。所以一个行程可以使用多个类别。

虽然我是个菜鸟,但我还是在 RoR 指南的帮助下解决了一些问题。现在,我有一个第三个表tripcategories,它必须保存trip_id 和category_id。正确的?有了它,我有以下模型:

trip.rb:

class Trip < ActiveRecord::Base
  attr_accessible :description, :title, :user_id, :triplocations_attributes, :photo
  has_many :triplocations, :dependent => :destroy

  has_many :tripcategories
  has_many :categories, :through => :tripcategories

  accepts_nested_attributes_for :triplocations, allow_destroy: true
end

category.rb:

class Category < ActiveRecord::Base
  attr_accessible :name
  has_many :tripcategories
  belongs_to :trip, :through => :tripcategories
end

tripcategory.rb:

class Tripcategory < ActiveRecord::Base
  attr_accessible :category_id, :trip_id
  belongs_to :trip
  belongs_to :category
end

当我尝试这种方式并尝试在我的旅行索引中调用trip.categories 时,它会显示"Unknown key: through"。我做错了什么,还是我错过了大局?

提前致谢!

【问题讨论】:

    标签: ruby-on-rails associations has-many-through


    【解决方案1】:
    class Category < ActiveRecord::Base
      attr_accessible :name
      has_many :tripcategories
      has_many :trips, :through => :tripcategories
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-16
      • 1970-01-01
      • 1970-01-01
      • 2019-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多