Answer the question
In order to leave comments, you need to log in
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
class CreateBoardsUsers < ActiveRecord::Migration
def change
create_table :boards_users do |t|
end
end
end
Answer the question
In order to leave comments, you need to log in
And why at you the table empty is created? It should contain user_id and board_id columns.
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
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
add_index :boards_users, :board_id
add_index :boards_users, :user_id
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question