2016-11-09 87 views
0

我有一個TaskTick。用戶創建Task後,我想自動創建Tick如何在初始化對象後自動創建對象?

def create 
     @task = current_user.tasks.build(task_params) 

     @task.category_id = params[:category_id] 

     respond_to do |format| 
      if @task.save 
       format.html { redirect_to tasks_path, notice: 'Task was successfully created.' } 

      # @task.ticks.build(user_id: @user, complete: false) # doesn't create tick, but shows no error 
      # Tick.create(user_id: @user.id, tick_id: @tick.id, complete: false) #error: undefined method `id' for nil:NilClass 
      else 
       format.html { render :new } 
      end 
    end 
    end 

蜱型號:

class Tick < ApplicationRecord 
    belongs_to :task 
    belongs_to :user 
end 

任務模型

class Task < ApplicationRecord 
    belongs_to :user 
    belongs_to :category 
    has_many :ticks 
end 

我已經嘗試了所有的答案來自this similar question

這一點,就行了上述respond_to do |format|

@task.ticks.build(user_id: @user, complete: false) 

(會拋出NoMethodError在#創建...未定義的方法`爲無地圖」任務:NilClass)


我以後if @task.save

@task.ticks.build(user_id: @user, complete: false) 

(沒有按這些過不創建勾號,但不顯示錯誤)

Tick.create(user_id: @user.id, tick_id: @tick.id, complete: false) 

(拋出錯誤:無未定義的方法`ID」:NilClass)


此外,有沒有什麼,我試圖做一個技術叫什麼名字?

+0

嘗試這個@ @ task.ticks.create(user_id:current_user.id,complete:false)' – sa77

+1

解決@ sa77 - 謝謝隊友 –

回答

1

您可以用模型回調實現這一

class Task < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :category 
    has_many :ticks 

    after_create :set_tick 

    private 

    def set_tick 
    self.ticks.create!(user: self.user, complete: false) 
    end 
end 
1

修改創建行動按照下面,你並不需要建立類對象,只是初始化類的對象與當前用戶參考。

def create 
     @task = current_user.tasks.new(task_params) 

     @task.category_id = params[:category_id] 

     respond_to do |format| 
      if @task.save 
       format.html { redirect_to tasks_path, notice: 'Task was successfully created.' } 

      # @task.ticks.build(user_id: @user, complete: false) # doesn't create tick, but shows no error 
      # Tick.create(user_id: @user.id, tick_id: @tick.id, complete: false) #error: undefined method `id' for nil:NilClass 
      else 
       format.html { render :new } 
      end 
    end 
    end 

在這裏,您不需要將user_id指定給您的對象。