如何使用表单与多态关联

时间:2017-02-12 23:41:14

标签: ruby-on-rails forms erb polymorphic-associations

我正在尝试在我的new.html.erb页面上创建一个表单,它给了我一个未定义的方法`task_presentations_path'错误。

= form_tag [@task, Presentation.new] do |f|
    = f.label :summary
    = f.text_field :summary

tasks_controller

def new
    @task = Task.new
end

路由

resources :presentations do
        resources :tasks
    end

任务模型

class Task < ApplicationRecord
  belongs_to :taskable, polymorphic: true
  has_one :task_type
  has_one :task_status
end

演示模型

class Presentation < ApplicationRecord
    has_many :tasks, as: :taskable
end

rake任务

          presentation_tasks GET      /presentations/:presentation_id/tasks(.:format)               tasks#index
                             POST     /presentations/:presentation_id/tasks(.:format)               tasks#create
       new_presentation_task GET      /presentations/:presentation_id/tasks/new(.:format)           tasks#new
      edit_presentation_task GET      /presentations/:presentation_id/tasks/:id/edit(.:format)      tasks#edit
           presentation_task GET      /presentations/:presentation_id/tasks/:id(.:format)           tasks#show
                             PATCH    /presentations/:presentation_id/tasks/:id(.:format)           tasks#update
                             PUT      /presentations/:presentation_id/tasks/:id(.:format)           tasks#update
                             DELETE   /presentations/:presentation_id/tasks/:id(.:format)           tasks#destroy

1 个答案:

答案 0 :(得分:0)

由于您的task模型是nested资源presentation原来,因此仅当存在presentation模型时才存在。所以......

######in the controller.

def new
   @presentation  = Presentation.find(params[:id)   
   @task = @presentation.tasks.new
end

#####in your view
= form_tag [@presentation,@task] do |f|
   ....
   ....

希望有所帮助:)