初始化对象后如何自动创建对象?

时间:2016-11-09 02:23:29

标签: ruby-on-rails

我有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 #infine ...未定义方法`map&#39; for nil: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&#39;对于nil:NilClass)

此外,我还有一个技术名称吗?

2 个答案:

答案 0 :(得分: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 :(得分:0)

按照以下修改您的创建操作,您不需要构建类对象,只需使用当前用户引用初始化您的类对象。

    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分配给您的对象。