2017-12-27 492 views
0

使用設備的任務,不能創建任務 我的模型 用戶無法創建色器件

class User < ApplicationRecord 
    # Include default devise modules. Others available are: 
    # :confirmable, :lockable, :timeoutable and :omniauthable 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable 

    has_many :tasks 
end 

任務

class Task < ApplicationRecord 
    belongs_to :user 
end 

任務控制器

def create 
    @task = Task.new(task_params) 

    respond_to do |format| 
     if @task.save 
     format.html { redirect_to @task, notice: 'Task was successfully created.' } 
     format.json { render :show, status: :created, location: @task } 
     else 
     format.html { render :new } 
     format.json { render json: @task.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

,並試圖在創建任務有錯誤

1錯誤禁止被保存在這個任務:

User must exist 

我的反應

開始POST 「/任務」 爲127.0.0.1,在2017年12月27日14時20分59秒0200 處理由TasksController#創建以HTML 參數:{ 「UTF8」=> 「✓」, 「authenticity_token」=> 「b7EkQsJygYBW1xLIm1uFD8jluXy2LYeoYjAOjKcwWOMHLwtalXmkTrNJu0yhexucwY94COegDcuVrOWLRkf8dg ==」, 「任務」=> { 「標題」=> 「」,「描述「=>」「,」優先「=>」「,」due(1i)「=>」2017「,」due(2i)「=>」12「,」due(3i)「=>」27「 ,「完成」=>「0」},「提交」=>「創建任務」}

User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ? [["id", 2], ["LIMIT", 1]] 
    (0.0ms) begin transaction 
    (0.1ms) rollback transaction 

怎麼了?

回答

0

更改belongs_to :userbelongs_to :user, optional: true。 Rails 5引入了關聯中的默認驗證。請參閱this link更好地理解

+0

它的工作原理,但不是正確的。當我添加到new_task_view

\n <%= form.label :user_id %>\n <%= form.text_field :user_id, id: :task_done %>\n
\ n它的工作原理我whant,但我需要勉強把用戶的ID。我希望自動執行此操作 – asda111sd

0

的方法創建控制器需要添加@task.user_id = current_user.id

+0

這不能提供問題的答案。要批評或要求作者澄清,請在其帖子下方留言。 - [來自評論](/ review/low-quality-posts/18362806) – Mamun

+0

這是一個答案。它可以使用更多的解釋,但它是一個答案。 –

0

你丟失了user_id創建task

嘗試以下

在你的代碼

def create 
    @task = Task.new(task_params) 

    respond_to do |format| 
    if @task.save 
     format.html { redirect_to @task, notice: 'Task was successfully created.' } 
     format.json { render :show, status: :created, location: @task } 
    else 
     format.html { render :new } 
     format.json { render json: @task.errors, status: :unprocessable_entity } 
    end 
    end 
end 

從您的代碼修改,您可以使用

def create 
    @task = Task.new(task_params) 
    @task.user = current_user 

    respond_to do |format| 
    if @task.save 
     format.html { redirect_to @task, notice: 'Task was successfully created.' } 
     format.json { render :show, status: :created, location: @task } 
    else 
     format.html { render :new } 
     format.json { render json: @task.errors, status: :unprocessable_entity } 
    end 
    end 
end 

希望幫助