Cap*_*arl 3 ruby-on-rails associations has-many-through
我正在我的 rails 应用程序中创建行程,我想为这些行程添加类别。类别存储在我的数据库的类别表中,用户可以选择适合旅行的类别。所以一个行程可以使用多个类别。
虽然我是一个菜鸟,但我在有关这个主题的 RoR 指南的帮助下想出了一些事情。现在,我有一个第三个表tripcategories,它必须保存trip_id 和category_id。对?有了它,我有以下模型:
旅行.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
Run Code Online (Sandbox Code Playgroud)
类别.rb:
class Category < ActiveRecord::Base
attr_accessible :name
has_many :tripcategories
belongs_to :trip, :through => :tripcategories
end
Run Code Online (Sandbox Code Playgroud)
tripcategory.rb:
class Tripcategory < ActiveRecord::Base
attr_accessible :category_id, :trip_id
belongs_to :trip
belongs_to :category
end
Run Code Online (Sandbox Code Playgroud)
当我以这种方式尝试并尝试在我的旅行索引中调用 trip.categories 时,它说"Unknown key: through"。我做错了什么,还是我错过了大局?
提前致谢!
class Category < ActiveRecord::Base
attr_accessible :name
has_many :tripcategories
has_many :trips, :through => :tripcategories
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3107 次 |
| 最近记录: |