简体   繁体   English

如何在Rails的数据库中保存参数?

[英]How do I save parameters in the database in rails?

My rails app has an Operator model and a Booking model and they are related by the following relation: 我的rails应用程序具有一个运营商模型和一个预订模型,它们之间的关系如下:

class Booking < ActiveRecord::Base
    belongs_to :operator
end

My app further allows users to find cabs at a particular day and time, from a pickup location to a drop location, and book the cab, after checking the fares, thus creating an entry in the Booking model in the database. 我的应用程序还允许用户在特定的日期和时间(从接送地点到放下地点)查找出租车,并在检查票价后预订出租车,从而在数据库的Booking模型中创建一个条目。 When creating a new booking, the user is presented with a typical form ('user_form') where they enter their name and other details. 创建新的预订时,系统会向用户显示一个典型的表单('user_form'),在其中输入其姓名和其他详细信息。 These details are stored in the bookings table in the database in appropriate columns. 这些详细信息存储在数据库中预订表的适当列中。

I want my app to be able to store three more parameters in the bookings table, without these parameters being filled up through the user_form. 我希望我的应用程序能够在预订表中存储另外三个参数,而无需通过user_form填写这些参数。 These parameters are: pickup location, drop location and the fare. 这些参数是:上车地点,下车地点和票价。

The pickup and the drop locations are filled up by the user while searching the cabs, whereas the fare parameter is displayed to the user after making some internal calculations based on business logic. 用户在搜索出租车时会填满接送地点,而在根据业务逻辑进行了一些内部计算后,票价参数会显示给用户。 I can't pass these parameters as params , as these are sensitive parameters, and if tampered, they can have negative consequences for the business. 我不能将这些参数作为params传递 ,因为它们是敏感参数,如果被篡改,它们可能会对业务产生负面影响。

My bookings table has appropriate columns to store these parameters. 我的预订表有适当的列来存储这些参数。 Also, my bookings_controller allows these parameters to be saved as strong parameters. 另外,我的bookings_controller允许将这些参数另存为强参数。 How do I save these three parameters in my bookings table while creating a new booking for an operator? 在为运营商创建新预订时,如何在预订表中保存这三个参数? Can furnish more details if required. 如果需要,可以提供更多详细信息。

I would use attr_accessor to store the relevant params from the form, and then have a before_validation method to look at these and calculate the fare. 我将使用attr_accessor来存储表单中的相关参数,然后使用before_validation方法查看这些参数并计算票价。 This can do the calculation for the fare and write it into the database. 这样就可以计算票价并将其写入数据库。 eg 例如

#in booking
attr_accessor :foo


before_validation :calculate_fare_if_foo


def calculate_fare_if_foo
  unless self.foo.blank?
    #do some calculation based on foo and the other attributes, to set self.fare
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM