0

我正在尝试在 Rails 5 中制作一个应用程序来发布任务的答案。

任务内容与答题形式在同一页面。

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

他可以发布(创建)答案或编辑答案。

我收到一个错误:

NoMethodError in Tasks#show undefined method `to_key' for # 你的意思是?to_query to_set to_ary

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

我真的很感激任何帮助!


楷模

```

# task.rb



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

结尾

# 答案.rb

class Answer < ApplicationRecord
 belongs_to :task
 belongs_to :user
end

```

路线.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>

```

4

1 回答 1

2

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

 @answer = Answer.where(task: @task, user: current_user).first
于 2017-03-20T05:15:13.147 回答