简单形式 - 嵌套资源路径

Simple Form for - Nested Resources paths

我正在尝试在 Rails 5 中制作一个应用程序以 post 回答任务。

任务内容和答案表格在同一页面。

用户进入任务页面后,可以看到任务内容。

并且他可以post(创建)答案或编辑答案。

我收到一个错误:

NoMethodError in Tasks#show undefined method `to_key' for # Did you mean? to_query to_set to_ary

我做错了什么? 您还需要哪些信息来帮助调试此问题?

非常感谢任何帮助!


型号

```

# task.rb



class Task < ApplicationRecord
 belongs_to :post
 has_many :answers, dependent: :destroy

结束

#answer.rb

class Answer < ApplicationRecord
 belongs_to :task
 belongs_to :user
end

```

routes.rb

```

resources :tasks, only: [:show] do
 resources :answers #, only: [:new, :create, :edit, :update]

结束

```

控制器

```

# tasks_controller.rb

class TasksController < ApplicationController
  before_action :authenticate_user!, only: [:show]

  def show
    @task = Task.find(params[:id])
    @post = @task.post

    if @task.answers.present?
      @answer = Answer.where("task_id = ? and user_id = ?", @task.id, current_user.id)
    else
      @answer = Answer.new
    end
  end


 end


# answers_controller.rb

def new
  @task = Task.find(params[:task_id])
  @answer = Answer.new
end

def create
  @task = Task.find(params[:task_id])
  @answer = Answer.new(answer_params)
  @answer.task_id = @task.id
  @answer.user_id = current_user.id

  if @answer.save
    redirect_to post_path(@task.post), notice: "Answer Added."
  else
    render :new
  end

结束

```

观看次数

```

<div class="answer-form">
<%= simple_form_for [@task, @answer], :url => task_answer_path(@task, @answer), method: :put  do |f| %>
  <% if @task.answers.present? %>
   <%= f.input :content, id: "x", value: @task.answers.first.content,
               input_html: {class: "hidden"}, name: "content", label: false %>
   <trix-editor input="x" class="formatted_content trix-content"></trix-editor>

   <div class="form-actions">
     <%= f.submit "Submitting", class: "assignment-btn", data: {disable_with: "Submitting..."} %>
   </div>
<% end %>

<% else %>

   <%= simple_form_for [@task, @answer], :url => task_answers_path(@task), method: :post do |f| %>
                <%= f.input :content, id: "x", value: "content",
                            input_html: {class: "hidden"}, name: "content", label: false %>
                <trix-editor input="x" class="formatted_content trix-content"></trix-editor>

                <div class="file-upload-block">
                    <input name="fileToUpload[]" id="fileToUpload" type="file">
                </div>

                <div class="form-actions">
                  <%= f.submit "提交", class: "assignment-btn", data: {disable_with: "Submitting..."} %>
                </div>
               <% end %>


<% end %>
</div>

```

我知道可能出了什么问题,下面这行返回的是 ActiveRecord::Relation,而不是实例本身,您需要在答案查询的末尾附加 'first',例如:

 @answer = Answer.where(task: @task, user: current_user).first