Reputation: 968
I have a problem with get value from :days new form.
new.html.haml
= f.select :days, [['1 month', 30], ['2 months', 60], ['3 months', 90]]
controller
def create
@bought_detail = BoughtDetail.new(bought_detail_params)
@bought_detail.entry_type = @entry_type
@bought_detail.person = current_person
if @bought_detail.entry_type.kind == 'Karnet'
@bought_detail.cost = @bought_detail.entry_type.price * (days / 30).floor
else
@bought_detail.cost = @bought_detail.entry_type.price
end
end
private
def bought_detail_params
params.require(:bought_detail).permit(:bought_data, :start_on, :end_on, :entry_type_id, :days, :person_id, :credit_card, :card_code)
end
Model
belongs_to :entry_type
belongs_to :person
before_save :set_bought_data, :set_end_on, :set_start_on
attr_accessor :credit_card, :card_code, :days
def set_bought_data
self.bought_data = Date.today
end
def set_start_on
self.start_on = bought_data if start_on.nil?
end
def set_end_on
days = "7" if days.nil?
self.end_on = Date.today + days.to_i
end
When I fill new form and click submit I get this error:
undefined local variable or method `days'
I want to deliver value from select field e.g. when I choose 2 months, value of the day will be 60
and I will can get calculate @bought_detail.cost
. How to do this?
Thanks in advance!
Upvotes: 0
Views: 166
Reputation: 18444
In controller you're trying to access undefined variable days
, change to accessing the model:
@bought_detail.cost = @bought_detail.entry_type.price * (@bought_detail.days.last / 30).floor
In model change to:
self.days = "7" if days.nil?
because otherwise you'll be assigning to local variable, not the attribute.
Upvotes: 1
Reputation: 11813
In your controller's create
method. Where are you getting the days
from?
@bought_detail.cost = @bought_detail.entry_type.price * (days.last / 30).floor
This bit specifically: days.last / 30
. Ruby can't find days
method or local variable. I guess you want to access it from params[:your_model][:days]
?
Upvotes: 0