提供以下型號: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
我想設置在房間表中的新數據2
到day
列當我添加一個房間。
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
如果你能給我任何建議,我們將不勝感激。
感謝您的快速回復,@ dkp。我想知道如何將此值+1設置爲新記錄。 – SamuraiBlue