Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails 4-如何在创建时设置db属性_Ruby On Rails - Fatal编程技术网

Ruby on rails Rails 4-如何在创建时设置db属性

Ruby on rails Rails 4-如何在创建时设置db属性,ruby-on-rails,Ruby On Rails,这似乎是一个愚蠢的问题,但如何从模型方法更新数据库字段?incident.incident_number值显示在所有表单和电子邮件上,但在数据库中为空: 事件。rb validate :incident_number, :on => :save def incident_number (self.created_at.strftime("%Y") + self.created_at.to_date.jd.to_s + self.id.to_s).to_i end

这似乎是一个愚蠢的问题,但如何从模型方法更新数据库字段?incident.incident_number值显示在所有表单和电子邮件上,但在数据库中为空:

事件。rb

 validate :incident_number, :on => :save

  def incident_number
    (self.created_at.strftime("%Y") + self.created_at.to_date.jd.to_s + self.id.to_s).to_i
  end
  def create
    @incident = Incident.new(incident_params)
    @incident.user_id = current_user.id
    @incident.state_id = 1
    respond_to do |format|
      if @incident.save
        IncidentMailer.new_incident_notification(@incident).deliver
        format.html { redirect_to my_incidents_path, notice: 'Incident was successfully created.' }
        format.json { render action: 'show', status: :created, location: @incident }
      else
        format.html { render action: 'new' }
        format.json { render json: @incident.errors, status: :unprocessable_entity }
      end
    end
  end
事件\u controller.rb

 validate :incident_number, :on => :save

  def incident_number
    (self.created_at.strftime("%Y") + self.created_at.to_date.jd.to_s + self.id.to_s).to_i
  end
  def create
    @incident = Incident.new(incident_params)
    @incident.user_id = current_user.id
    @incident.state_id = 1
    respond_to do |format|
      if @incident.save
        IncidentMailer.new_incident_notification(@incident).deliver
        format.html { redirect_to my_incidents_path, notice: 'Incident was successfully created.' }
        format.json { render action: 'show', status: :created, location: @incident }
      else
        format.html { render action: 'new' }
        format.json { render json: @incident.errors, status: :unprocessable_entity }
      end
    end
  end

您当前的方法不会持久化到数据库,它只是在每次调用该方法时运行逻辑

有很多方法可以做到这一点-或者通过(在保存前工作良好)

或者,使用


有几种方法可以去除这只猫的皮肤,试试看,根据触发的回调以及它们如何处理记录/更改的属性,您更喜欢哪种方法。

您当前的方法不会保留到数据库中,它只是在每次调用该方法时运行逻辑

有很多方法可以做到这一点-或者通过(在保存前工作良好)

或者,使用

有几种方法可以剥除这只猫的皮,试试看,根据触发的回调以及它们如何处理您的记录/更改的属性,您更喜欢哪种方法