简单表单 - 嵌套资源路径

时间:2017-03-20 04:55:55

标签: ruby-on-rails simple-form-for

我正在尝试在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

```

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

```

1 个答案:

答案 0 :(得分:2)

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

var addNew=true;
if (score == 5 && addNew) {
  spawnNewEnemies();
  addNew=false;
}