我想用Rails 4製作一個論壇應用程序。我希望用戶有很多論壇,所以我知道我需要一個多對多的關係。我有一個表格來保存標題和新論壇的描述。我目前有3個表,用戶,論壇和forums_users。當我創建一個新表單並將其添加到論壇數據庫時,一切都很好。我的問題是我如何獲取信息去forums_users表?因爲現在當我提交表單時,它不會將信息添加到關聯表中。 這是我的論壇遷移文件。如何在rails中製作多對多關聯
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
這些是我的模型。
class Forum < ActiveRecord::Base
has_and_belongs_to_many :users
end
class User < ActiveRecord::Base
has_and_belongs_to_many :forums
end
這是我在論壇控制器
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
創建方法和這裏是你提交表單。
= 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
在此先感謝您。