简体   繁体   中英

Rails4: How to set max value + 1

Give the following models:

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

class Room < ActiveRecord::Base
  belongs_to :schedule
end

What I'd like to do is to set the maximum value + 1 to the added data.

For example, before update

Day 1
schedule_title A
    room_name A

after update,

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

I'd like to set 2 to day column for new data in the rooms table when I add next room.

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

When I press "Add room" button and update after entering some, I'd like to set maximum value + 1 to day for new data in room table.

_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

It would be appreciated if you could give me any suggestion.

Room.maximum(:day)

应该在“房间”表的“天”列中给您最大值。

There are two approaches.

Approach 1: Do it Yourself

Try the following:

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

Approach 2: Use an existing implementation

Take a look at acts_as_list . There position is equivalent to your date .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM