繁体   English   中英

Rails AssociationTypeMismatch错误我想不出来

[英]Rails AssociationTypeMismatch error I can't figure out

我对rails(和ruby)很陌生,我遇到了一个似乎很简单的问题,但我一直无法弄清楚我做错了什么。 在下面的代码示例中,我设置了Project,Attribute和User模型及其关联。 另外,我已经包含了迁移代码,以防我的问题出现。

看起来很简单,但是当我在rails控制台中执行以下操作时:

proj = Project.create(:name => 'first project', :link => 'http://www.me.com', :ownerid => 1, :desc => 'First project description', :active => true)

我收到此错误:

ActiveRecord::AssociationTypeMismatch: Attribute(#2162685940) expected, got Array(#2151973780)

那么我做错了什么呢? 我认为rails认为它应该获得一个属性,而是获得一个数组,但我不明白为什么。 我可以成功创建一个属性或用户,当我从Project模型中删除'has_many:attributes'时,我可以成功创建一个Project。

class Project < ActiveRecord::Base
  has_many :users
  has_many :attributes
end

class Attribute < ActiveRecord::Base
  belongs_to :project
end

class User < ActiveRecord::Base
  has_and_belongs_to_many :project
end

class CreateProjects < ActiveRecord::Migration
  def self.up
    create_table :projects do |t|
      t.string  :name
      t.string  :link
      t.integer :owner  #user_id#
      t.text    :desc
      t.boolean :active
      t.timestamps
    end
  end

  def self.down
    drop_table :projects
  end
end

class CreateAttributes < ActiveRecord::Migration
  def self.up
    create_table :attributes do |t|
      t.string  :name
      t.integer :project_id
      t.timestamps
    end
  end

  def self.down
    drop_table :attributes
  end
end

class CreateUsers < ActiveRecord::Migration
  def self.up
    create_table :users do |t|
      t.string  :email
      t.string  :password
      t.boolean :active
      t.boolean :admin
      t.string  :location
      t.string  :phone
      t.timestamps
    end
  end

  def self.down
    drop_table :users
  end
end

Attribute是保留字,因此您应该重命名模型。 实际上保留的是attributes= method。 因此,当您创建关联has_many :attributes您将重写标准方法

这是API: attributes =attributes

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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