【问题标题】:Active Record how to add records to has_many :through association in railsActive Record 如何将记录添加到 has_many :通过rails中的关联
【发布时间】:2014-12-11 11:56:47
【问题描述】:

我的 has_many 有很大的问题:通过关联。 模型如下所示:

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

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

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

我在 DatasetController 中的创建方法如下所示:

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

我尝试了&lt;&lt; 运算符和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

【问题讨论】:

  • 你能发布你的schema.rb吗?仅 3 个模型中的一个
  • 谢谢,这是我现在的问题..

标签: ruby-on-rails ruby activerecord has-many-through


【解决方案1】:

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

所以您只需要创建一个迁移来添加这些列:

class AddRefererColumnsToRole < ActiveRecord::Migration
  def change
    add_column :roles, :user_id, :integer
    add_column :roles, :dataset_id, :integer
  end
end

【讨论】:

  • 谢谢!由于模型之间的依赖关系,我认为这会被添加。但这可能太容易了。现在工作正常,谢谢:)
猜你喜欢
  • 2012-01-01
  • 2011-11-09
  • 2012-10-24
  • 2014-12-27
  • 1970-01-01
  • 1970-01-01
  • 2016-08-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多