繁体   English   中英

Active Record如何通过rails中的关联将记录添加到has_many:

[英]Active Record how to add records to has_many :through association in rails

我的has_many:through关联有很多问题。 这些模型如下所示:

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

我想在每次创建新数据集时向角色添加一条记录。 它应该使用新的数据集创建,现有用户“ Admin”和“角色”的列名应设置为“ Admin”。

我尝试了在Stackoverflow上找到的所有内容,但对我没有任何帮助。

我在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

我尝试了<<操作符和create方法。

第一个结果是:

ActiveRecord::UnknownAttributeError in DatasetsController#create
unknown attribute: dataset_id

第二个:

ActiveModel::MissingAttributeError in DatasetsController#create
can't write unknown attribute `user_id

有谁知道为什么我会收到这些错误?

我的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

您的Role模型需要一些列来引用它所属的UserDataset 没有这些,就不知道谁属于谁。

因此,您只需要创建一个迁移即可添加以下列:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM