这是一件容易的事,但我无法找到错误的地方。我有一个模型User(Devise),它有很多功能。看起来像这样:
/app/model/user.rb
class User < ActiveRecord::Base
has_many :features
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :first_name, :last_name, :email, :password, :date_of_birth, :gender, :password_confirmation
# attr_accessible :title, :body
validates_inclusion_of :gender, :in => ['female', 'male'], message: 'not selected'
validates :first_name, presence: true
validates :last_name, presence: true
validates_date :date_of_birth, :on_or_before => lambda { Date.current }
end
/app/model/feature.rb
class Feature < ActiveRecord::Base
belongs_to :user
attr_accessible :content, :hits, :icon, :images, :lable, :rank, :success, :user_id
end
但是Rails魔法根本不起作用:
rails console
user = User.create(email: 'test@test.de', password: 'test', password_confirmation: 'test', first_name: 'Test', last_name: 'Test', date_of_birth: '1992-12-21 00:00:00.000000', gender: 'male')
feature = user.feature.create(content: 'First Feature', hits: 5, icon: 'icon-bell', images: null, lable: 'Bell', rank: 1, success: 3)
返回错误:
NoMethodError: undefined method `feature' for #<User:0x4b377b8>
我阅读了很多帖子,但我找不到任何错误。有人可以给我一个提示,我认为这是我犯的这样一个愚蠢的错误。谢谢!
答案 0 :(得分:1)
你必须这样做
feature = user.features.create(content: 'First Feature', hits: 5, icon: 'icon-bell', images: null, lable: 'Bell', rank: 1, success: 3)
因为用户has_many:为用户创建功能时必须输入功能而不是功能
feature = user.features.create