【发布时间】:2017-04-30 21:33:57
【问题描述】:
我正在尝试做一个简单的任务:我创建了一个“杂志”脚手架,但我希望它具有特定的关系:用户可以参与杂志的创建/编辑,这可能需要几个用户创建杂志。
我检查了 APIDock 并执行了以下操作:
- 指定杂志和用户之间的关系
model/magazine.rb
class Magazine < ApplicationRecord
mount_uploader :thumbnail, ThumbnailUploader
has_and_belongs_to_many :users
end
model/user.rb
class User < ApplicationRecord
has_and_belongs_to_many :magazines
# More code...
end
-
创建了一个迁移以添加一个表来链接两个模型
class ManyToMany < ActiveRecord::Migration[5.0] def change create_table :magaziness_users, :id => false do |t| t.integer :user_id t.integer :magazine_id end add_index :magazines_users, [:magazine_id, :user_id] end end
然后我运行迁移
-
将曾经记录到数据库中的所有用户的列表添加到创建下拉列表
<div class="field"> <%= f.label :users %> <%= f.select :users, User.all_except(current_user).collect {|u| [u.username, u]}, {prompt: 'Add a creator?'}, { :multiple => true, :size => 3 } %> </div>
但是,当我保存新杂志时,用户没有被保存,并且“magazines_user 仍然为空。
编辑 1
这是一个自动生成的控制器,因为我使用脚手架命令来创建它。除了 set_magazine 函数,我没有碰任何东西,我在其中添加了 Friendly_Id
class MagazinesController < ApplicationController
before_action :set_magazine, only: [:show, :edit, :update, :destroy]
def index
@magazines = magazine.all
end
def show
end
def new
@magazine = magazine.new
end
def edit
end
def create
@magazine = magazine.new(magazine_params)
if @magazine.save
redirect_to @magazine, notice: 'magazine was successfully created.'
else
render :new
end
end
def update
if @magazine.update(magazine_params)
redirect_to @magazine, notice: 'magazine was successfully updated.'
else
render :edit
end
end
def destroy
@magazine.destroy
redirect_to magazines_url, notice: 'magazine was successfully destroyed.'
end
private
def set_magazine
@magazine = magazine.friendly.find(params[:id])
end
def magazine_params
params.require(:magazine).permit(:titre, :description, :apercu, :users)
end
end
我是不是忘记了什么步骤?
【问题讨论】:
-
请发布您的控制器代码。
-
我添加了控制器
-
我从未将这种方法用于多对多关系......更好的方法是使用“有很多通过”......在这里阅读:guides.rubyonrails.org/…
-
问题是我真的不需要其他实体,我只需要说明谁参加了哪些杂志,哪些杂志可以在谁的个人资料上找到..
-
您的迁移中没有错字:create_table :magaziness_users 吗?同样奇怪的是,在您的控制器中,您的“magazine.new”不应该是:Magazine.new?
标签: ruby-on-rails model many-to-many entity-relationship