0

I'm looking to create simple categories in my Rails app, with a lot of searching through the internet and finding tutorials which are too abstract I am now posting on here for some guidance/help.

What I currently have is a Posts scaffold which belongs to a User which works perfectly. I think I need to setup a many to many relationship between categories and posts which allows a post to belong to multiple categories - Also creating a link to the category which lists the posts that belong to it.

Posts can belong to multiple categories

How would I go about adding this to my project or creating something on the lines of this?

Thanks,

Jonathan

Jonathan
  • 673
  • 1
  • 10
  • 32
  • http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association, what do you mean by too abstract – Mohammad AbuShady Mar 26 '15 at 19:29
  • you can also go for HABTM(has_and_belongs_to_many) http://guides.rubyonrails.org/association_basics.html – Sonalkumar sute Mar 26 '15 at 19:50
  • What I'm unsure on and is abstract is how to go about inserting this into my app as well as integrating selects into the view etc. Fairly new to rails and struggling around these concepts – Jonathan Mar 26 '15 at 19:52
  • Check this: http://stackoverflow.com/questions/5120703/creating-a-many-to-many-relationship-in-rails-3 – Laerte Mar 26 '15 at 21:41
  • so make a categories table with each category name. Then make a join table called post_categories that will have the foreign keys for posts and categories. A post has many categories through post_categories. then something like PostCategories.where(category_id: category.id).includes(:posts). I am not sure exactly about the query but I would just test it in console until I had the correct return. – ruby_newbie Mar 26 '15 at 21:42

1 Answers1

2

Check out this link: Creating a many to many relationship in Rails 3

In your case, your code should probably look like this:

# app/models/post.rb
class Post < ActiveRecord::Base
  belongs_to :user
  has_and_belongs_to_many :categories
end

# app/models/category.rb
class Category < ActiveRecord::Base
  has_and_belongs_to_many :posts
end

# db/migrate/1213123123123_create_categories_posts_join_table.rb
class CreateCategoriesPostsJoinTable < ActiveRecord::Migration
  def change
    create_table :categories_posts, :id => false do |t|
      t.integer :category_id
      t.integer :post_id
    end
  end
end
Community
  • 1
  • 1
DarkSun
  • 451
  • 1
  • 7
  • 19