【问题标题】:ActiveModel::ForbiddenAttributesError When Creating New `Task`ActiveModel::ForbiddenAttributesError 创建新的“任务”时
【发布时间】:2016-12-12 12:43:57
【问题描述】:

我在尝试 create 新的 task 时收到 ActiveModel::ForbiddenAttributesError。我想我已经消除了所有愚蠢的错误,所以我很乐意帮助解决它。

我的tasks_controller如下:

class TasksController < ApplicationController
  def index
    @tasks = current_user.Task.all
  end

  def create
    @task = Task.new(params[:task])  <<<<<<<<<<<THIS LINE
    @task.user = current_user
    if @task.save
      flash[:notice] = "Your exercise results were saved!"
      redirect_to tasks_path
    else
      render :action => 'new'
    end
  end

  def new
    @task = Task.new
  end

  def edit
    @task = Task.find(params[:id])
  end

  def update
    @task = Task.find(params[:id])
    if @task.update_attributes(params[:task])   <<<<<<<<<<<THIS LINE
      redirect_to tasks_path
  end

  def destroy
    @task = Task.find(params[:id])
    @tasks.destroy
    redirect_to tasks_path
  end

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

  private

  def task_params
    params.require(:task).permit(:name, :reps, :weight, :comments, :user_id)
  end

  end
end

在指示的两条线上,我尝试了params[:task] 和'task_params'。第一个抛出ForbiddenAttributesError;后者为#`抛出undefined local variable or methodtask_params'。

这是我的tasks#newerb:

  <%= form_for @task do |f| %>
  <div class="col-xs-12">
    <%= f.label "Exercise Name" %>
    <%= f.text_field :name, class: "form-control" %>
    </div>
    <div class="col-xs-6">
      <%= f.label "Reps" %>
      <%= f.number_field :reps, class: "form-control" %>
    </div>
    <div class="col-xs-6">
      <%= f.label "Weight" %>
      <%= f.text_field :weight, class: "form-control" %>
    </div>
    <div class="col-xs-12">
      <%= f.label "Comments/Notes" %>
      <%= f.text_field :comments, class: "form-control" %>
    </div>

    <div class="text-center"><%= f.submit "Record Exercise", class: "btn-primary" %></div>
  <% end %>

最后,我的schematasks如下,所以我知道变量的名字是对的:

  create_table "tasks", force: :cascade do |t|
    t.string   "name"
    t.integer  "user_id"
    t.integer  "reps"
    t.integer  "weight"
    t.text     "comments"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

谁能指导我修复这个“Ruby 方式”?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    试试这个:

    def create
     @task = Task.new(task_params)  ##change here
     @task.user = current_user
     if @task.save
      flash[:notice] = "Your exercise results were saved!"
      redirect_to tasks_path
     else
      render :action => 'new'
     end
    end
    

    【讨论】:

    • 这会引发undefined local variable or method 'task_params' for #&lt;TasksController:0x007fcabe872748&gt;
    • 在您的更新方法中,缺少一个“结束”。也许你已经在 def 'task_params' 的末尾添加了它。请更正。
    • 天哪……它总是有些愚蠢。谢谢!
    猜你喜欢
    • 2013-06-24
    • 1970-01-01
    • 2016-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多