N
N
Nodar2016-05-09 21:30:48
Ruby on Rails
Nodar, 2016-05-09 21:30:48

Rails 4 many_to_many, how to set it up correctly?

Hey! Can't figure out how to set up relationships in Rails via an intermediate table.
Models

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  has_and_belongs_to_many :boards, join_table: :boards_users
  has_many :tasks
end

class Board < ActiveRecord::Base
  belongs_to :owner, class_name: "User"
  has_and_belongs_to_many :user, join_table: :boards_users
  has_many :tasks, dependent: :destroy
end

Migration
class CreateBoardsUsers < ActiveRecord::Migration
  def change
    create_table :boards_users do |t|
    end
  end
end

How do I add entries to boards_users? Will the rails somehow cope with this themselves or do you need to prescribe something with pens? I made a BoardBoards model and tried to save, but the relation "boards_users" doesn't exist error keeps popping up.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Eugene Burmakin, 2016-05-09
@Freika

And why at you the table empty is created? It should contain user_id and board_id columns.

C
Chronic 86, 2016-05-20
@chronic86

class CreateBoardsUsers < ActiveRecord::Migration
  def change
    create_table :boards_users, id: false do |t|
     t.integer :board_id
     t.integer :user_id
    end
  end
end

It's better to name the migration CreateBoardsUsersJoinTable.
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  has_and_belongs_to_many :boards
  has_many :tasks
end

class Board < ActiveRecord::Base
  belongs_to :owner, class_name: "User"
  has_and_belongs_to_many :users
  has_many :tasks, dependent: :destroy
end

When writing has_and_belongs_to_many the model name is plural. In your code: user
If necessary, you can add indexes to join_table:
add_index :boards_users, :board_id
add_index :boards_users, :user_id

When you correct your models, the rails themselves will build the necessary associations.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question