2013-10-25 94 views
0

它是如此簡單的事情,但我無法找到問題所在。我有一個模型用戶(設計)誰有很多功能。看起來是這樣的:Rails n:1關係不起作用

/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: '[email protected]', 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> 

我讀了很多帖子,但我找不到任何錯誤。有人能給我一個提示,我認爲它是我犯的這樣一個愚蠢的錯誤。謝謝!

+1

你大概的意思'features',不特徵。用戶有很多*功能*。所以調用user.features.create() – calas

回答

1

你有,因爲用戶的has_many做

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

:你必須輸入功能,而不是功能用戶創建一個功能,當功能

feature = user.features.create 
+0

謝謝,這是行得通!我只需添加一個user.save,然後添加一個功能即可。但是什麼是錯誤的,當功能控制器根本不工作?它始終將user_id設置爲null,並且在控制器本身中,不能訪問@user對象。控制器由rails g scaffold生成...。準備在create方法中保存值的函數是「@feature = Feature.new(params [:feature])」。 – neonmate

+0

還有一點值得注意:它工作時,我在「@feature = Feature.new(params [:feature])」下添加了「@ feature.user_id = current_user.id」這一行,但爲什麼它在控制檯中使用put? – neonmate

+0

我並沒有完全明白你的意思是控制檯輸入,但從我的理解你有麻煩設置user_id.As你說你可以做@ feature.user_id = current_user.id或者你可以嘗試做一些像current_user.features .create特性#create – Brock90