Rails4:如何设置最大值+ 1

提供以下型号:

class Schedule < ActiveRecord::Base has_many :rooms accepts_nested_attributes_for :rooms, allow_destroy: true end class Room < ActiveRecord::Base belongs_to :schedule end 

我想要做的是为添加的数据设置最大值+ 1。

例如,在更新之前

 Day 1 schedule_title A room_name A 

更新后,

 Day 1 schedule_title A room_name A Day 2 # I'd like to set `2` to `day` column in room table schedule_title B room_name B 

当我添加下一个房间时,我想为房间表中的新数据设置2day列。

schema.rb

  create_table "rooms", force: :cascade do |t| t.string "name" t.integer "schedule_id" t.integer "day", default: 1 ... end create_table "schedules", force: :cascade do |t| t.string "title" t.integer "user_id" t.date "departure_date" ... end 

当我按下“添加房间”按钮并在输入一些后更新,我想为房间表中的新数据设置最大值+ 1到day

_schedule_form.html.erb

      

schedlues_controller.rb

 class SchedulesController < ApplicationController ... def update if @schedule.update(schedule_params) flash[:success] = "schedule updated!" redirect_to root_url else render 'edit' end end ... private def schedule_params params.require(:schedule).permit(:title, :departure_date, rooms_attributes: [:id, :_destroy, :room, :day]) end 

如果你能给我任何建议,我们将不胜感激。

 Room.maximum(:day) 

应该在房间表的日栏中给你最大值。

有两种方法。

方法1:自己动手

请尝试以下方法:

 class Schedule < ActiveRecord::Base has_many :rooms accepts_nested_attributes_for :rooms, allow_destroy: true end class Room < ActiveRecord::Base belongs_to :schedule before_create :set_date protected def set_date if self.date.nil? self.date = self.schedule.rooms.collect(&:date).max + 1 end true end end 

方法2:使用现有实现

看看acts_as_list 。 这个position相当于你的date