我有一個Task
和Tick
。用戶創建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)
此外,有沒有什麼,我試圖做一個技術叫什麼名字?
嘗試這個@ @ task.ticks.create(user_id:current_user.id,complete:false)' – sa77
解決@ sa77 - 謝謝隊友 –