Rails application with legacy database

时间:2018-03-22 23:53:39

标签: ruby-on-rails ruby

I'm building an API that will look for data in a "non-rails-database". It already exists and was not created with the rails project. What is the best approach to use in this case ? Let's say I have a table called User in this database, I would like to be able to do something like this in the controller: User.last or User.find(id). It would be good, because I have to send back to the frontend as a JSON. Should I use PORO Models ? How would it be ?

3 个答案:

答案 0 :(得分:1)

我个人更喜欢将它们放在PORO中。对我而言,它使事情变得清晰,并提供更大的灵活性。

例如,我在api_models文件夹中有一个名为app的单独文件夹,并在那里有类。

首先,您可能觉得您正在复制代码,但它会为您提供一个在API需求更改时使用的对象。

E.g

ApiModel::User
  ...  
end

另外,

如果你想要更多的进步并考虑版本控制(如果不是你应该;)等,我会推荐一个像grape这样的宝石,因为它可以处理很多与api相关的事情,所有你需要关注的是代码。

答案 1 :(得分:1)

创建模型,然后显式设置表名和主键,这有助于您在控制器中调用活动记录方法

class User < ApplicationRecord
 self.primary_key = 'user table primary key'
 self.table_name = 'user table name'
end

参考http://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/PrimaryKey/ClassMethods.html http://api.rubyonrails.org/classes/ActiveRecord/ModelSchema/ClassMethods.html#method-i-table_name-3D

答案 2 :(得分:0)

我会创建自定义方法,其中包含覆盖ActiveRecord方法的自定义数据库查询。因为模型类继承自ActiveRecord,所以如果在模型类中使用与ActiveRecord方法相同的方法名定义方法,则在调用它时,将调用模型类。如果您拨打super

,仍然可以调用ActiveRecord方法

因此,假设您已经设置了与DB的连接,您可以执行以下操作:

class User < ApplicationRecord

  def self.find(id)
    sql = "Select * from ... where id = ..."
    records_array = ActiveRecord::Base.connection.execute(sql)
  end
end

因此,当您致电查找时,它会拨打User find,而不是ActiveRecord find。您还可以定义自定义方法,以便不覆盖ActiveRecord find

class User < ApplicationRecord

  def self.new_find(id)
    sql = "Select * from ... where id = ..."
    records_array = ActiveRecord::Base.connection.execute(sql)
  end
end

不确定它是否是最好的方法,但它是一种方法:)