3

I'm creating trips in my rails app and i want to add categories to those trips. The categories are stored in the Categories table in my DB and the user may select which categories are suitable for the trip. So multiple categories a trip can be used.

Although i'm a noob i figured some things out with some help of the RoR guides about this subject. Now, i've got a 3rd table tripcategories which will have to hold the trip_id and the category_id. Right? With that i've got the following models:

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

When i'm trying it this way and trying to call trip.categories in my trip index it says "Unknown key: through". Am i doing something horribly wrong or am i missing the bigger picture?

Thanks in advance!

1 Answer 1

5
class Category < ActiveRecord::Base
  attr_accessible :name
  has_many :tripcategories
  has_many :trips, :through => :tripcategories
end

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.