2016-04-12 133 views
0

所以我有一個嵌套的資源,其中todolist是父項,todoitem是孩子。Rails嵌套資源(新)

resources :todolists do 
    resources :todoitems 
end 

我已經創建了一個Add Todo List鏈接,它會調用routes.rb發現new_todolist_todoitem

new_todolist_todoitem GET /todolists/:todolist_id/todoitems/new(.:format)  todoitems#new 

在我todolists/show.html.erb文件,我已經包括了這行代碼:

<%= link_to 'Add Todo Item', new_todolist_todoitem_path(@todolist.id) %> 

在我todoitems/_form.html.erb,我也包括它裏面嵌套參數:

<%= form_for([@todolist, @todoitem]) do |f| %> --> Error is on this line 
    <% if @todoitem.errors.any? %> 
<div id="error_explanation"> 
    <h2><%= pluralize(@todoitem.errors.count, "error") %> prohibited this todoitem from being saved:</h2> 

在我的todoitems_controller.rb中,我把這些降爲newcreate方法:

# GET /todoitems/new 
    def new 
    @todoitem = Todoitem.new 
    end 

    # POST /todoitems 
    # POST /todoitems.json 
    def create 
    @todoitem = @todolist.todoitems.new(:todoitem_params) 

    respond_to do |format| 
     if @todoitem.save 
     format.html { redirect_to @todoitem, notice: 'Todoitem was successfully created.' } 
     format.json { render :show, status: :created, location: @todoitem } 
    else 
     format.html { render :new } 
     format.json { render json: @todoitem.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

的問題是,我不斷收到錯誤提示:

undefined method `todoitems_path' for #<#<Class:0x007feaa79e8da8>:0x007feaa5d0d878> 

如果有人有一個可能的解決方案來解決這個問題或建議,將不勝感激。謝謝!

P.S.根據堆棧跟蹤,參數請求是:{"todolist_id"=>"2"}

回答

0

有幾件事需要注意,希望它能解決您的問題。

在你todolists/show.html.erb,你可以通過@todolistlink_to

<%= link_to 'Add Todo Item', new_todolist_todoitem_path(@todolist) %>

這時需要您的控制器來進行一些改變:

todoitems_controller.rb

before_action :set_todolist 

def create 
    @todoitem = Todoitem.new(todoitem_params) 

    # Assuming Todoitem belongs_to Todolist 
    @todoitem.todolist_id = @todolist.id 
    ... 
end 

private 

def set_todolist 
    @todolist = Todolist.find(params[:todolist_id] 
end 

製作確保你的參數是正確的。

1

您未在控制器代碼中設置@todolist實例變量,但您在form_for [@todolist, @todoitem]標記中使用它。確保你的控制器中有一套。通常這是在before_filter像這樣完成:

class Todoitem 
    before_filter :set_todolist 

    def set_todolist 
    @totolist = Todolist.find(params[:todolist_id]) 
    end 
end 
+0

如果我已經這樣做了?我只是忘了把它包含在這個問題中。還有什麼我可以做的嗎?我檢查了是否有拼寫錯誤,但沒有任何... @uzbekjon – ETUDESC

+0

好吧,讓我們來看看。你正在'todoitems_path undefined'錯誤。所以,這意味着你的代碼正在嘗試訪問該路徑。讓我們弄清楚究竟發生了什麼。你能否包括你的錯誤的完整堆棧跟蹤? – Uzbekjon

+0

哦,我現在正在工作,但我很樂意發佈它,一旦我回來了......哈哈@uzbekjon – ETUDESC