Head First Railsの第6章を読了

第6章はパーシャルテンプレート、関連(has_many, belongs_to)、カスタムバリデータ。

RoRのバージョンの違いで書き方が変わっていたところのメモ。これまで特に断っていませんでしたが、たいてい前のバージョンの書き方でも動くようです。

# p.231
<%= render :partial => "new_seat"%>
 ↓
<%= render "new_seat"%>
# p.235
<%= render :partial => "new_seat", :locals => {:seat => Seat.new} %>
 ↓
<%= render "new_seat", :seat => Seat.new %>
# p.258
class Seat < ActiveRecord::Base
  belongs_to :flight
  def validate
    if baggage > flight.baggage_allowance
      errors.add_to_base("You have too much bggage")
    end
    if flight.seats.size >= flight.capacity
      errors.add_to_base("The flight is fully booked")
    end
  end
endclass Seat < ActiveRecord::Base
  belongs_to :flight
  
  # :allow_nilと:presenceは元のにはないですが、自分用メモのために追加
  validates :baggage, :baggage_allowance => {:allow_nil => true}, :presence => true
  validates_with SeatsSizeValidator
end

# app/validators/baggage_allowance_validator.rb を作成
class BaggageAllowanceValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    if options[:allow_nil] and value == nil
      return
    end
    if value > record.flight.baggage_allowance
      record.errors[attribute] << "You have too much baggage"
    end
  end
end

# app/validators/seats_size_validator.rb を作成
class SeatsSizeValidator < ActiveModel::Validator
  def validate(record)
    if record.flight.seats.size > record.flight.capacity
      record.errors[:base] << "The flight is fully booked"
    end
  end
end

新しい書き方で、カスタムバリデータを外に出せるのは便利ですね。

app/validatorsの下にファイルを作りましたが、これが一般的なのかどうかはわかりません。lib/validatorsの方が良いのかも。