【问题标题】:How to use form for with polymorphic associations如何将表单用于多态关联
【发布时间】:2017-02-12 23:41:14
【问题描述】:

我正在尝试在我的 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

收集任务

          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

【问题讨论】:

  • 我会运行 bundle exec rake routes | grep task 并查看该路线的名称。看起来可能是presentation_tasks_path,但我不确定
  • 你能补充更多控制器和型号的信息吗..?
  • 是的,我已经更新了。

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


【解决方案1】:

由于您的task 模型是presentationnested 资源,最初它应该只存在于存在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|
   ....
   ....

希望对你有帮助。

【讨论】:

  • 是的,我确实尝试过。当我这样做时,我得到的错误是表单上未定义的方法“tasks_path”
  • 更改表单参数...我已经更新了我的答案。作为其演示文稿/任务...您需要先将演示文稿传递给表单,然后再将任务传递给表单。检查我的答案。让我知道它是否有效:)。
  • 谢谢! :) 它确实有效。但是,现在我得到的错误是在标签上,未定义的方法“标签”为 nil:NilClass
  • 正如我所说,每个演示文稿都有一个任务,因此请验证演示文稿和任务是否存在然后检查它们的字段。您可以使用rails控制台快速检查模型及其列。请接受答案如果它对你有帮助。
  • tasks 有一个叫做summary 的字段,我不明白为什么它说它确实是一个列时它没有一个summary 字段
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多