【问题标题】:How to create an object automatically after initialising object?初始化对象后如何自动创建对象?
【发布时间】:2016-11-09 02:23:28
【问题描述】:

我有一个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) 

(在 Tasks#create 中抛出 NoMethodError ... undefined method `map' 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) 

(抛出错误:nil:NilClass 的未定义方法 `id')


另外,我正在尝试做的事情有技术名称吗?

【问题讨论】:

  • 试试这个@task.ticks.create(user_id: current_user.id, complete: false)
  • 已解决 @sa77 — 感谢伙伴

标签: ruby-on-rails


【解决方案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

【讨论】:

    【解决方案2】:

    如下修改你的创建动作,你不需要构建类对象,只需用当前用户引用初始化你的类对象。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-17
      • 1970-01-01
      • 1970-01-01
      • 2020-11-07
      • 2010-09-20
      • 2013-06-27
      相关资源
      最近更新 更多