2016年7月2日 星期六

使用form_for遭遇 undefined method 'xxxx_path' 問題處理

問題情境

我的routes設置如下:
Rails.application.routes.draw do
  resources :projects do
    resources :real_lives
  end
  root "projects#index"
end



controller設置如下:
def new    
    @project = Project.find(params[:project_id])
    @real_life = @project.real_lives.new()
  end

新增real_life時,在new.html.erb使用simple_form_for 發生Error,問題程式如:
    <%= form_for @real_life do |f| %>
        <%= f.label :schedule_type %>

        <%= f.text_field :schedule_type %>
    <% end %>

undefined method 'xxxx_path'的 錯誤訊息



問題原因

按Rails的設計 real_lives / new.html.erb對應的路徑應該是real_lives_path,但是因為Project與Real_Life資料結構的關係,所以在routes的設置,real_lives並不是獨立的路由,所以並不會有real_lives_path的路徑存在,錯誤的原因在此。所以必須在form_for或是simple_form_for指定url。

問題處理

把
<%= form_for @real_life do |f| %>
改為
<%= form_for @real_life, url: project_real_lives_path do |f| %>

沒有留言: