2012-02-16 70 views
0
class User < ActiveRecord::Base 
    has_many :microposts 
end 

class Mircopost < ActiveRecord::Base 
    belongs_to :user 
end 

ActiveRecord::Schema.define(:version => 20120216035330) do 

    create_table "mircoposts", :force => true do |t| 
    t.integer "user_id" 
    t.string "content" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    end 

    create_table "users", :force => true do |t| 
    t.string "name" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    end 

end 

我運行rake db:migrate,rails console並創建一個假用戶= User.create(:name =>「abc」)。但是,當我運行user.microposts.empty?時,它會產生「NameError:未初始化的常量User :: Micropost」。所以我不明白爲什麼這些方法是自動生成的。 在此先感謝!使用has_many後沒有創建關聯

+2

microposts或mircoposts ... one is mispelled – drhenner 2012-02-16 04:22:06

回答

1
has_many :microposts 
class Mircopost < ActiveRecord::Base 
1

你想CREATE_TABLE 「微柱」

CREATE_TABLE 「mircoposts」

然後

user.microposts

會存在

1

我遇到了這個不同的原因。我用腳手架命名爲「MicroPost」,因此rails創建了一個名爲micro_post.rb的模型,schema.rb文件創建了一個名爲「micro_posts」的表。而不是「has_many:microposts」,我不得不使用「has_many:micro_posts」,然後在控制檯中使用「first_user.micro_posts」。由於第二個大寫字母,Rails(或Ruby,不知道是哪個)自動插入了下劃線。