[英]Rails, calling model method from controller
A little new to Rails, but simply, I have a model method that calculates the date difference: Rails有点新,但是简单来说,我有一个模型方法来计算日期差:
def days_diff
(end_date.to_date - start_date.to_date).to_i + 1
end
I want to be able to use this value/method in my controller to loop a form field x number of times. 我希望能够在我的控制器中使用此值/方法来循环一次表单字段x次。 How do I about calling this method from the controller to use this variable?
如何从控制器调用此方法以使用此变量?
Thanks in advance! 提前致谢!
Say your model is named ModelName. 假设您的模型名为ModelName。 In your controller method you would have:
在控制器方法中,您将具有:
def controller_method
@model_name = ModelName.find(params[:id]) # or however you obtain your model
x = @model_name.days_diff
x.times do |index|
# call your loop stuff here
end
end
Try defining the method in your model as 尝试将模型中的方法定义为
self.days_diff
and then call it in the controller as 然后在控制器中以
model_name.days_diff
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.