我对质量分配和强大的参数有疑问。在我的模型中,我有几个属性,这些属性通过mysql数据库中的一列表示。我也有一个领域,不是。我只需要它来计算一个值。我不想将其存储在数据库中。
在我的控制器中,我定义了强参数:
def timeslots_params
params.require(:timeslot).permit(:employee_id, :dienstplan_id, :start_date, :start_time)
end
但是,当我尝试访问控制器中的start_time属性时,
undefined method `start_time' for #<Timeslot:0x007fff2d5d8070> error.
存在带有db列的其他已定义参数,并用值填充。我会误解强参数,还必须定义其他东西吗?
编辑:这是代码,我称之为timeslots_params:
def create
@e = Timeslot.new(timeslots_params)
@e.start_date = @e.start_date.to_s + " " + @e.start_time.to_s
if @e.save
current_user.timeslots << @e
respond_to do |format|
format.json { render :json => @e }
end
end
end
请仅允许您希望用户随数据一起发送的参数。如果start_time不是用于更新数据库的用户数据,请使用以下方式:
params.require(:timeslot).permit(:employee_id, :dienstplan_id, :start_date)
强大的参数可防止保存用户发送的数据,并且您不希望他/她进行更新。
如果使用:start_time,则必须在模型上定义它。
操作,我已经看到了您的更新:
@e.start_date = @e.start_date.to_s + " " + @e.start_time.to_s
如果您将:start_time发送到一个Timeslot实例,则它们start_time必须是Timeslot模型的方法。由rails定义(如果它是db字段),由attr_accesor或att_reader定义,或由源模型上的def键定义。
如果不@e.start_time
触发undefined method 'start_time'
。
再次编辑:
现在,start_time是一个模型变量。确保以与对字段相同的方式将其发送到表单。默认情况下,我们使用f <%= f.text_field :the_field %>
。只是不要忘记f。
现在,如果您遵循我的第一个建议,则必须再次允许该字段。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句