Ruby/Rails - Access a “lookup” table without modeling it?

时光毁灭记忆、已成空白 提交于 2019-12-09 17:58:20

问题


This is for a Ruby on Rails 3.0.x project.

I have a "lookup" table with data from a vendor.

When I import data from another source, I want to check this table (join on a SKU) for extra data.

It doesn't seem right to me to create a model for this table in my app. The data will never be changed by my app, and it doesn't need to have any model associations beyond the data lookup I just mentioned. It's just occasionally accessed to check for some info.

What is the best practice to access this table?

Thanks.


回答1:


There's no harm in creating a model around it, but if you'd like to avoid it, you will have to send raw SQL queries to the DB to get data back as an alternative.

Raw queries: Rails raw SQL example

On the other hand, I think the motivation for wrapping a model around it goes beyond whether or not you want to modify it. I definitely have apps that have models around tables that never change (i.e. a list of app-specific terminology, a list of cities/states, and other static data that is imported once and never changed). ActiveRecord will also wrap the columns into easily accessible methods, so you can read that data easily, not to mention all the convenience methods around sorting, finding, etc.




回答2:


Another option is to store it in a YML, and then load that YML into a constant in your environment.rb file.

Like this:

 LOOK_UP_TABLE = YAML.load_file("#{RAILS_ROOT}/misc/vendor_data.yml")



回答3:


Why doesn't it seem right to create a model for... a model? If it's in the database, there's no reason not to have a model for it.

You might want to restrict its resource definition, or not map it at all, to avoid access. That said, it's likely you'd want to be able to update it: a web interface is an easy way to do that, whether file- or user-driven.

Other options include loading it from a config file (Yaml, XML, vendor-specific), retrieving it from a service, etc. Those solutions could be stand-alone, or also leverage a model-backed approach.



来源:https://stackoverflow.com/questions/8052755/ruby-rails-access-a-lookup-table-without-modeling-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!