简体   繁体   中英

Fields parameters with hyphen in Ruby on Rails

Rails adopt camelcase or underscore naming convention and this is given.

But what if the data that is to be stored in a Rails app has different naming conventions?

For example an 3rd party API may return some parameters as 'fieldId' but also as 'field-id'.

In the case of a parameter like 'field-id' how can a MVC be designed in Rails to accommodate this scenario? If a resource is named 'field_id' Rails simply ignore the parameter 'field-id' and the data is not saved - good thing from security perspective, but still the business problem is present.

Any ideas?

It is quite normal that a third party system does not conform with your own internal structure. You can try to change your own structure, but normally should just build something that translates between the external and the internal structure. This is so common that there is are several pattern for this, for example the : adapter-pattern

If you want some more specific advice, you need to be more specific yourself, what is this API, how do you access it. If you are talking about HTTP-Post-Parameters, you just write a method that take a hash as input and outputs another hash, with different key names.

You can customize field name in ActiveRecord. If you want to ignore default convention of rails and want to apply your own convention, here is how you can configure it : Example :

class Project < ActiveRecord::Base
  self.primary_key = 'sysid'
end

Now here primary key for projects table would be sysid and not id .

Here is good documentation of ActiveRecord class method primary_key http://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/PrimaryKey/ClassMethods.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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