我遇到以下问题:天新表格。
new.html.haml
= f.select :days, [['1 month', 30], ['2 months', 60], ['3 months', 90]]
控制器
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
模型
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
当我填写新表单并单击“提交”时,我收到此错误:
undefined local variable or method `days'
我想从选择字段中提供价值,例如当我选择2个月时,当天的价值将为60
,我可以计算@bought_detail.cost
。这该怎么做?
提前谢谢!
答案 0 :(得分:1)
在控制器中,您尝试访问未定义的变量days
,更改为访问模型:
@bought_detail.cost = @bought_detail.entry_type.price * (@bought_detail.days.last / 30).floor
在模型更改为:
self.days = "7" if days.nil?
因为否则你将分配给局部变量,而不是属性。
答案 1 :(得分:0)
在控制器的create
方法中。你从哪里得到days
?
@bought_detail.cost = @bought_detail.entry_type.price * (days.last / 30).floor
具体来说:days.last / 30
。 Ruby找不到days
方法或局部变量。我想你想从params[:your_model][:days]
访问它?