rails model attributes without corresponding column in db

岁酱吖の 提交于 2019-12-10 16:12:25

问题


I have some rails models which don't need any persistence, however I'd like rails to think the model actually has attributes x, y, z so when calling methods like to_json in the controller I get them included for free.

For example,

class ModelWithoutTableColumns << ActiveRecord::Base

def x
   return "Custom stuff here"
end

There is no column x in the database for Table "ModelWithoutTable" (sorry for the slightly confusing name!)

Anyone have an idea how to tackle this one?


回答1:


Sounds like you want ActiveModel. Check out http://yehudakatz.com/2010/01/10/activemodel-make-any-ruby-object-feel-like-activerecord/ for a great walkthrough by Yehuda Katz. Specifically the section called "Serialization" for your to_json requirements.




回答2:


Just don't inherit from ActiveRecord::Base

Edit: Have you tried passing options to to_json, like :methods perhaps? See here




回答3:


That won't work--ActiveRecord::Base defines to_json, but requires a table.

You should check out the ActiveRecord::BaseWithoutTable plugin. Here's how to use it, and here's an updated version for Rails 2.

I haven't tried either of them, so no guarantees.




回答4:


You might also want to check out acts_without_database, the current details about it are here, but the site is down at the moment. Here's the posting on RubyFlow, it's from today.



来源:https://stackoverflow.com/questions/399490/rails-model-attributes-without-corresponding-column-in-db

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