0

这是一件很容易的事情,但我无法找到问题所在。我有一个具有许多功能的模型用户(设计)。看起来像这样:

/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>

看了这么多帖子,没发现有什么错误。有人可以给我一个提示,我认为这是我犯的一个愚蠢的错误。谢谢!

4

1 回答 1

1

你所要做的

feature = user.features.create(content: 'First Feature', hits: 5, icon: 'icon-bell', images: null, lable: 'Bell', rank: 1, success: 3)

因为用户 has_many :features 为用户创建功能时,您必须键入 features 而不是 feature

feature = user.features.create
于 2013-10-25T08:25:02.043 回答