Rails AssociationTypeMismatch error I can't figure out
I'm pretty new to rails (and ruby) and I've run into what seems to be a simple problem but I've been unable to figure out what I'm doing wrong. In the code samples below I've setup Project, Attribute and User models and their associations. Additionally I've included the migration code in case my problem is there.
Seems simple enough, but when I do the following in the rails console:
proj = Project.create(:name => 'first project', :link => 'http://www.me.com', :ownerid => 1, :desc => 'First project description', :active => true)
I get this error:
ActiveRecord::AssociationTypeMismatch: Attribute(#2162685940) expected, got Array(#2151973780)
So what is it that I'm doing wrong? I get that rails is thinking it should be getting an Attribute but is instead getting an Array, but I don't understand why. I can successfully create an Attribute or a User, and when I remove the 'has_many :attributes' from the Project model I can successfully create a 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
is reserved word, so you should rename your model. Actually what is reserved is attributes=
method. So when you are creating association has_many :attributes
you are rewriting standart method
Here is API: attributes= and attributes
精彩评论