[英]Active Record how to add records to has_many :through association in rails
I have quite the Problem with my has_many :through association. 我的has_many:through关联有很多问题。 The models look like this:
这些模型如下所示:
class User < ActiveRecord::Base
has_many :roles
has_many :datasets, through: :roles
has_secure_password
end
class Role < ActiveRecord::Base
belongs_to :user
belongs_to :dataset
end
class Dataset < ActiveRecord::Base
has_many :roles
has_many :users, through: :roles
end
I want to add a record to roles every time a new Dataset is created. 我想在每次创建新数据集时向角色添加一条记录。 It should be created with the new Dataset, an existing User 'Admin' and the column name of Role should be set to 'Admin'.
它应该使用新的数据集创建,现有用户“ Admin”和“角色”的列名应设置为“ Admin”。
I tried everything I found on Stackoverflow but nothing works for me. 我尝试了在Stackoverflow上找到的所有内容,但对我没有任何帮助。
My create method in the DatasetController looks this: 我在DatasetController中的 create方法如下所示:
def create
@dataset = Dataset.new(dataset_params)
@dataset.save
@user = User.find_by(name: 'Admin')
@dataset.users << @user
#@dataset.roles.create(user: @user, dataset: @dataset, name: 'Admin')
respond_with(@dataset)
end
I tried both the <<
operator and the create
method. 我尝试了
<<
操作符和create
方法。
the first results in: 第一个结果是:
ActiveRecord::UnknownAttributeError in DatasetsController#create
unknown attribute: dataset_id
the second in: 第二个:
ActiveModel::MissingAttributeError in DatasetsController#create
can't write unknown attribute `user_id
Does anyone know why I get these errors? 有谁知道为什么我会收到这些错误?
my schema.rb: 我的schema.rb:
create_table "datasets", force: true do |t|
t.string "name"
t.text "description"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "roles", force: true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "users", force: true do |t|
t.string "name"
t.string "mail"
t.string "password_digest"
t.datetime "created_at"
t.datetime "updated_at"
end
Your Role
model needs columns to refer to which User
and Dataset
it belongs. 您的
Role
模型需要一些列来引用它所属的User
和Dataset
。 Without these it has no idea who belongs to who. 没有这些,就不知道谁属于谁。
So you simply need to create a migration to add these columns: 因此,您只需要创建一个迁移即可添加以下列:
class AddRefererColumnsToRole < ActiveRecord::Migration
def change
add_column :roles, :user_id, :integer
add_column :roles, :dataset_id, :integer
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.