Rails4:如何设置最大值+ 1

时间:2016-03-25 21:21:11

标签: ruby-on-rails ruby ruby-on-rails-4

提供以下型号:

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

<%= simple_nested_form_for(@schedule) do |f| %>

  <%= f.label :title %>
  <%= f.text_field :title, class: 'form-control' %>
  <%= f.label :departure_date %>
  <%= f.text_field :departure_date, class: 'form-control' %>

  <div id="room">
    <%= f.simple_fields_for :rooms do |r| %>
      <%= r.input :room %>
    <% end %>
    <%= f.link_to_add "Add room", :rooms, data: {target: '#room'}, class: "btn btn-primary" %>
  </div>

<% end %>

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

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

2 个答案:

答案 0 :(得分:0)

Room.maximum(:day)

应该在房间表的日期栏中为您提供最大值。

答案 1 :(得分:0)

有两种方法。

方法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_listposition等同于date