2016-11-09 96 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指定给您的对象。