rails attribute changes in spite of not being in form

前端 未结 2 873
鱼传尺愫
鱼传尺愫 2021-01-16 07:01

I have rails app where users can assign tasks to each other. Every task has one assigner and one executor. By default the task creator(current_user) is always the assigner.

相关标签:
2条回答
  • 2021-01-16 07:46

    By default the task creator(current_user) is always the assigner

    This should not matter - someone is the assigner and someone is the executor.


    miler350 is correct - your params are constantly setting your assigner_id: current_user.id (looks like one of my suggestions).

    The fix is to remove the .merge from your params & set it in your controller action (as per miler350's answer & like this):

    #app/controllers/tasks_controller.rb
    class TasksController < ApplicationController
    
        def new
            @task = Task.new
        end
    
        def create
            @task = Task.new task_params
            @task.assigner = current_user
            @task.save
        end
    
        def edit
            @task = Task.find params[:id]
        end
    
        def update
            @task = Task.find params[:id]
            @task.update task_params
        end
    
        private
    
        def task_params
            params.require(:task).permit(:executor_id, :name, :content, :deadline, :task_name_company, :assigner_id)
        end
    
    end
    

    By letting users "edit" an assignment, you should not have different assigner / executor defined each time.

    0 讨论(0)
  • 2021-01-16 07:56
    def task_params
      params.require(:task).permit(:executor_id, :name, :content, :deadline, :task_name_company).merge(assigner_id: current_user.id)
    end
    

    You are setting the assigner id to current_user every time you pass in the params.

    I would remove the merge, and just have strong params like this:

    params.require(:task).permit(:executor_id, :name, :content, :deadline, :task_name_company, :assigner_id)
    

    Then, in your create action, before you do:

    @task.save
    

    Add this:

    @task.assigner_id = current_user.id
    

    Then you can define your permissions however you choose (must be assigner, must be executor), but as long as you don't add anything crazy to update, it'll work fine.

    0 讨论(0)
提交回复
热议问题