【问题标题】:Simple form for not working on belongs to不工作的简单表格属于
【发布时间】:2018-08-23 02:33:56
【问题描述】:

您好,我有一个简单的 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

查看视图/目标/显示

<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>

表单视图/任务/_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)

所以我在我的目标控制器中添加了以下内容

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

【问题讨论】:

  • 你希望这个表单能做什么?
  • @Gabbar 创建与目标关联的任务...属于目标
  • 你有嵌套的任务路由吗?
  • 否,因为我希望用户能够以列表的形式访问他们的 current_user.tasks.all
  • 你能显示你的路线吗?

标签: ruby-on-rails simple-form has-many belongs-to


【解决方案1】:

根据 Jagdeep 上面的评论添加 Try added @task = @goal.tasks.build in goal_controller#show 修复了这个问题。

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2016-08-21
    • 1970-01-01
    • 2021-09-04
    • 1970-01-01
    • 1970-01-01
    • 2016-06-11
    • 1970-01-01
    • 2017-01-22
    • 1970-01-01
    相关资源
    最近更新 更多