2012-08-14 21 views
0

我是Rails的新手,我偶然發現了這個問題。我猜這對你的專業人員來說會相對簡單。我有一個名爲User的模型,它具有其中的所有用戶屬性。我還創建了一個名爲list的模型,現在我想要。我現在想調用的方法從用戶創建購買做這樣的事情如下(控制檯中的所有事情)Ruby on Rails項目中的未定義錯誤

sample = User.create(#attributes here) 
newlist = sample.List.create(#attributes here) 

然後我得到這個錯誤

irb(main):011:0> sample.Lists.new 
NoMethodError: undefined method `Lists' for #<User:0x4146750> 

下面是我的模型文件用戶和列表

# == Schema Information 
# 
# Table name: users 
# 
# id     :integer   not null, primary key 
# firstName   :string(255) 
# middleName   :string(255) 
# lastName   :string(255) 
# email    :string(255) 
# facebookexternalId :integer 
# userType   :integer 
# gender    :string(255) 
# description  :string(255) 
# location   :string(255) 
# image    :string(255) 
# password   :string(255) 
# notificationId  :string(255) 
# disabled   :boolean 
# disabledNotes  :string(255) 
# city    :string(255) 
# country   :string(255) 
# joinDate   :string(255) 
# created_at   :datetime   not null 
# updated_at   :datetime   not null 

class User < ActiveRecord::Base 

    attr_accessible :firstName, :middleName , :lastName ,:email , :facebookexternalId, :gender , :description, :location , :image , :city, :country, :disabled 
    email_regex= /\A[\w+\-.][email protected][a-z\d\-.]+\.[a-z]+\z/i 
    validates :firstName , :presence =>true, 
          :length => {:maximum => 45} 
    validates :lastName , :presence =>true, 
          :length => {:maximum => 45} 
    validates :email , :presence =>true, 
        :format =>{:with => email_regex}, 
        :uniqueness => {:case_sensitive => false} 
    validates :description, :length => {:maximum => 140} 

    has_many :lists 
end 

列表

# == Schema Information 
# 
# Table name: lists 
# 
# id   :integer   not null, primary key 
# name  :string(255) 
# user_Id  :integer 
# active  :boolean 
# type  :string(255) 
# description :string(255) 
# roughList :boolean 
# created_at :datetime   not null 
# updated_at :datetime   not null 
# 

class List < ActiveRecord::Base 
    belongs_to :user 
end 

回答

3

你應該使用它的列表複數形式,這將是這樣的,

sample_user.lists.create ...

sample_user.lists.new

怎麼樣,你在把它命名爲:的has_many

+0

你速度更快。 ; o) – 2012-08-14 22:07:21

+0

非常感謝!你真的讓我意識到我犯的另一個錯誤。我沒有將外鍵約束應用於主用戶表的ID。再次感謝! – 2012-08-14 22:39:34