2016-03-25 7 views
0

1が与える次のモデル:私が何をしたいのですがどのようなRails4:最大値を設定する方法+

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 

私はいくつかを入力した後、ボタンやアップデート「部屋を追加」を押し、私は部屋のテーブルに新たなデータのためにdayに最大値+ 1を設定したいと思います。

_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 

あなたが私にどんな提案を与えることができればそれをいただければ幸いです。

答えて

0
Room.maximum(:day) 

部屋のテーブルの日の列に最大値を指定する必要があります。

+0

ご連絡ありがとうございます。@ dkp。私はこの値+ 1を新しいレコードに設定する方法を知りたいです。 – SamuraiBlue

0

2つのアプローチがあります。

アプローチ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を見てみましょ既存の実装

を使用してください。 positiondateに相当します。

+0

@Dharamさん、ありがとうございます。 「アプローチ1」を試しましたが、その日は増分しません(まだ1です)。 "schedule_id" =?[0 "[" "schedule_id"、249] "[1m [36m(0.4ms)[0m [1mSELECT MAX("部屋 " ] 'が出力されました。だから、私はSQLの '' select max(day) '' schedule_id = 249; ''結果が '' 1 ''の部屋から試しました。 – SamuraiBlue

関連する問題