Doctor06
Doctor06

Reputation: 697

How to make a many to many association in rails

I am trying to make a forum application with Rails 4. I want users to have many forums and so I know I need a many-to-many relationship. I have a form to save the title and the description of the new forum. I Have 3 tables so far, users, forums, and forums_users. Everything works great when I create a new form and it gets added to the forums database. My question is how do I get the information to go to the forums_users table? Because right now when I submit my form, it does not add the information to the association table. Here is my migration file for forums.

def up
  create_table :forums do |t|
    t.string :title
    t.text :description
    t.string :logo
    t.boolean :is_active, default: true
    t.timestamps
  end
  add_index :forums, :title
  create_table :forums_users, id: false do |t|
    t.belongs_to :forum, index: true
    t.belongs_to :user, index: true
  end
end
def down
  drop_table :forums
  drop_table :forums_users
end

These are my models.

class Forum < ActiveRecord::Base
  has_and_belongs_to_many :users
end

class User < ActiveRecord::Base
  has_and_belongs_to_many :forums
end

Here is my create method in the Forum Controller

def create
  @forum = Forum.new(forum_params)
  @forum.save
  respond_to do |format|
    format.html{redirect_to admin_path, notice: 'New forum was successfully created.'}
  end
end
private
def forum_params
  params.require(:forum).permit(:title, :description, :logo, :is_active)
end

And here is the form you submit.

= simple_form_for(:forum, url: {action: :create, controller: :forums}) do |f|
  = f.error_notification
  .form-inputs
    = f.input :title, autofocus: true
    = f.input :description, as: :text
  .form-actions
    = f.button :submit

Thank you in advance.

Upvotes: 0

Views: 61

Answers (2)

Rajarshi Das
Rajarshi Das

Reputation: 12320

If you want to get the data from your join table forum_users then use has_many :through

  class Forum < ActiveRecord::Base
    has_many :users, through: :forum_users
  end

  class User < ActiveRecord::Base
    has_many :forums, through: :forum_user 
  end


  class ForumUser < ActiveRecord::Base
    belongs_to :user
    belongs_to :forum
   end

Now you can access/fetch the forum_users table data using UserForum Model

Upvotes: 1

scrapcode
scrapcode

Reputation: 45

Create the forum using a reference to the current user, for example:

@forum = current_user.forums.create(forum_params)

Upvotes: 0

Related Questions