2013-05-10 79 views
0

在路線:嵌套資源與Ruby的獨立意見型號名稱錯誤on Rails的

resources :users do 
    resources :service_exps 
end 

用戶模型:

has_many :service_exps 

service_exps型號:

belongs_to :user 

在service_exps控制器新動作:

def new 
    user = User.find(params[:user_id]) 
    @service_exp = user.service_exps.build 
    render :layout => false 
end 

在service_exps形式:

= form_for ([@service_exp.user, @service_exp]), :remote => true do |s| 
.modal-body 
    .row 
    .span 
     = s.label :org_name 
     = s.text_field :org_name, :class => "span3" 
    .row 
    .span 
     = s.label :position 
     = s.text_field :position, :class => "span3" 
    .actions 
    = s.submit 'Save',:class => "btn btn-info" 

它給錯誤

undefined method `user' for nil:NilClass 

請給予任何建議來解決這個問題。謝謝!

+0

您確定您要達到service_exps控制器的新操作嗎? – 2013-05-10 05:36:50

+0

hey santhosh,如果在@ service_exp.user上單擊(ctrl + click),它會轉到新的操作。 – Rajeev 2013-05-10 05:52:34

回答

0

這些類型的錯誤很容易調試。錯誤消息說明了一切。您正在調用一個方法(在本例中爲'user')一個無對象。

遵循以下步驟:

  • 查找文件,並從錯誤味精號線
  • 找到零的對象。
  • 確認對象被正確
0

首先初始化:@service_exp = user.service_exps.build將對象的數組指派給@service_exp - 由於用戶誰has_many :service_exps

在你看來,你在做@service_exp.user - 調用一個不能工作的對象數組的用戶。但是,像@service_exp.first.user這樣的東西雖然會在數組中的特定對象上調用用戶時發生。或者從form_for刪除.user

+0

Carter shaw如果我刪除.user或添加@ service_exp.first.user比它給出錯誤'undefined model_name' – Rajeev 2013-05-10 10:47:12

+0

在您的控制器中加載特定的service_exp而不是它們的陣列 – 2013-05-10 11:00:16

+0

您可以不只是調用service_exp.new(通過參數)在你的新動作? – 2013-05-10 11:14:47