Two Tables Serving as one Model in Rails

家住魔仙堡 提交于 2019-12-12 21:18:14

问题


Is is possible in rails to setup on model which is dependant on a join from two tables? This would mean that for the the model record to be found/updated/destroyed there would need to be both records in both database tables linked together in a join. The model would just be all the columns of both tables wrapped together which may then be used for the forms and so on. This way when the model gets created/updated it is just one form variable hash that gets applied to the model?

Is this possible in Rails 2 or 3?


回答1:


It isn't possible to do exactly what you're asking for in Rails as far as I know, but you can effectively accomplish what you're trying to accomplish with a second model, using callbacks and a has_one association, for instance:

class Widget < ActiveRecord::Base
  has_one :thingy
  before_save :save_thingy_object

  def save_thingy_object
    self.thingy = Thingy.new({ :attr1 => 'some', :attr2 => 'thing' })
  end
end

class Thingy < ActiveRecord::Base
  belongs_to :widget
end



回答2:


Multi-table inheritance has no out-of-the-box solution in Ruby on Rails right at the moment. Although i would suggest trying to do something similar as the aforementioned models with relations, and then basically abusing delegates or manual proxies to fake the relation attributes to appear as real attributes of the model.




回答3:


In MySQL you could try to work with views to join the two tables. But I am not sure what happens if records needs to be updated and how Rails would manage that.

http://dev.mysql.com/doc/refman/5.1/en/create-view.html



来源:https://stackoverflow.com/questions/3066847/two-tables-serving-as-one-model-in-rails

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