不工作的简单形式属于
Simple form for not working on belongs to
你好,我有一个简单的 rails 应用程序,它有两个模型,一个目标和一个任务
目标有多个任务,一个任务属于一个目标。
出于某种原因,可能是菜鸟错误,我无法将表单获取到任务表单以使用简单表单呈现。
型号
目标
class Goal < ApplicationRecord
has_many :tasks
end
任务
class Task < ApplicationRecord
belongs_to :goal
end
控制器
目标
class GoalsController < ApplicationController
before_action :set_goal, only: [:show]
def show
end
private
def set_goal
@goal = Goal.find(params[:id])
end
end
查看views/goals/show
<div class="row">
<%= @goal.title %>
<div class="row">
<ul>
<% @goal.tasks.each do |task| %>
<li><%= task.name %></li>
<% end %>
</ul>
<%= render partial: 'tasks/form', locals: {comment: @goal.tasks.new} %>
</div>
表格views/tasks/_form
<%= simple_form_for([@goal, @task]) do |f| %>
<div class="form-inputs">
<%= f.input :name %>
<%= f.input :description %>
</div>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
我在目标#show
中收到错误NoMethodError
很明显我需要将@task 添加到我的目标显示中....但是如何
所以我添加了我的目标显示方法
@task = Task.find_or_create_by(:task_id)
然后我得到错误
Unsupported argument type: task_id (Symbol)
所以我将以下内容添加到我的 goals_controller
def show
@task = Goal.task.find_or_create_by(:task_id)
end
但后来我得到
NoMethodError in GoalsController#show
undefined method `task' for #<Class:0x00007ff8c79b0920> Did you mean? take
路线
Rails.application.routes.draw do
resources :tasks
resources :goals
end
根据上面 Jagdeep 的评论,添加尝试在 goals_controller#show 中添加 @task = @goal.tasks.build 解决了这个问题。
希望这对您有所帮助