我正在尝试在Rails 5中创建一个应用程序来回答任务。
任务内容和答案表单在同一页面中。
当用户进入任务页面时,他可以看到任务内容。
他可以发布(创建)答案或编辑答案。
我收到错误:
任务中的NoMethodError#show #的未定义方法`to_key' 你的意思是? to_query 设置 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
```
```
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>
```
答案 0 :(得分:2)
我知道可能有什么问题,下面这行是返回一个ActiveRecord :: Relation,而不是实例本身,你需要在答案查询的末尾附加'first',如下:
var addNew=true;
if (score == 5 && addNew) {
spawnNewEnemies();
addNew=false;
}