anon
anon

Reputation: 634

Need advice on creating Models in Ruby on Rails

I plan to create a site for famous animals on the web, the homepage#index will display all the animals, and on the homepage, there will be some filters, to filter through Dogs, Cats, Others.

Now, being new to Rails, I am having a hard time figuring out how to set up a model like this.

If I create an Animal model,

rails g model Animal name:string description:string

Where do I exactly define a 'Dog, or Cat' to this particular item?

Do I need to add a category_id ?

rails g model Animal name:string description:string category_id:integer

What If I wanted the user to add/delete/edit the categories as well?

I am hoping someone can point me in the right direction.

Upvotes: 0

Views: 45

Answers (1)

c.early
c.early

Reputation: 186

I would suggest creating a Category model and an Animal Model:

class Category < ActiveRecord::Base
  acts_as_tree
  has_many :animals
end

class Animal < ActiveRecord::Base
  belongs_to :Category
end

In this way your animal could be a shark, which is also a fish. Or could be a cod, which is also a fish. If the user chose to view all fishes they would see sharks and cod, but if they chose to view cod they would not see sharks. Investigate 'acts_as_tree' for more info on this.

Should allow quite a lot of options for filtering! You would need a parent_id column in your categories migration, and a category_id column in your animals migration.

Upvotes: 1

Related Questions