2016-05-14 16 views
0

予約モデルの余分な費用の列が計算されず、新しい予約の作成時に保存されません。予約が編集されたときに計算され、保存されます(フォーム内の値を変更しなくても)。チェックボックスの値がcalculateメソッドなどで受信されていないようです。Railsの計算値がチェックボックスで機能しない

Reservation has_many :bookings, has_many :extras, :through => :bookings 
Booking belongs_to :extra, belongs_to :reservation 
Extra has_many :bookings, has_many :reservations, :through => :bookings 

before_save :calculate_extras_cost 

def calculate_extras_cost 
    self.extras_cost = self.extras.sum(:daily_rate) * total_days 
end 

<%=hidden_field_tag "reservation[extra_ids][]", nil %> 
<%Extra.all.each do |extra|%> 
    <%= check_box_tag "reservation[extra_ids][]", extra.id, @reservation.extra_ids.include?(extra.id), id: dom_id(extra)%> 
<% end %> 

答えて

1

使用して、代わりに手動で入力を作成するform collection helpers

<%= form_for(@reservation) do |f| %> 
    <%= f.collection_check_boxes(:extra_ids, Extra.all, :id, :name) %> 
<% end %> 

また、あなたが:extra_idsプロパティをホワイトリストされていることを確認してください。

コールバックを使用するときに気を付けなければならないもう1つのことは、子レコードがデータベースに挿入される前に親レコードをデータベースに挿入する必要があることです。つまり、self.extras.sum(:daily_rate)をコールバックに使用することはできません。これは、データベース内の子レコードに依存しているためです。

self.extras.map(&:daily_rate).sumを使用して、関連付けられたモデルの値をRubyのメモリから合計することができます。もう一つの選択肢はassociation callbacksです。

+0

フォームコレクションのヘルパーとアソシエーションコールバックに関するヒントをありがとう。あなたのソリューションは、私が変更した唯一のビットthats完全に動作します。 self.extras.map(&:daily_rate).sum –

関連する問題