0

I have the following problem in Rails which I am not sure how to solve. I build a test web application,a bulletin board with ads about real estate, like simple version of http://www.trulia.com/ and obviously users can add advertisements to the site which they can then find in their "office", and thats where the problem appears. I have 8 types of advertisements, like flats, offices, garages and etc, and so I need to be able to retrieve ads that belong to some particular user and I dont want to make sql requests to all 8 tables to show this user's advertisements, if user has , for example, just 1 ad about selling a flat. So I need something instead of

@garages = Garage.where("user_id = #{current_user.id}")
@flats = Flat.where("user_id = #{current_user.id}")
@offices = Office.where("user_id = #{current_user.id}")
..... and so on

I have User model so all ads belong to some user and I am thinking of creating a polymorphic table which would belong to user and contained information about all ads the user invited it would be named, for example,"Advertisement",it would have 3 columns, user_id, advertisable_id, advertiseble_type, and it would be very easy to get all rows that belong to some particular user, but I have no idea if its possible to make Rails get ads only from those tables that are in "advertisable_type" and with those ids from "advertisable_id", I hope you understand what I mean. So, any advices for a newbie? :)

4

1 回答 1

0

如果您现有的模型 Garage、Flat、Office 真的是广告,共享许多相同的逻辑和列,那么显然您需要重新设计数据。

如果它是 99% 相同的东西,为什么不只有Advertisement表和列advertisement_type?如果您想要广告类型的分类器,只需使用单独的表/模型并在您的表中AdvertisementTypes引用它们。advertisement_type_idadvertisements

如果您觉得有/将会有很多共同点,但也会有很多不同的逻辑,这可能是STI(单表继承)的理想案例。使用 STI 时,您有不同的模型类,它们继承自同一个父类并存储在同一个表中。

class Advertisement < ActiveRecord::Base
  def ad_text
    "We are selling property: #{read_attribute(:ad_text)}"
  end
end

class GarageAdvertisement < Advertisement
  def ad_text
    "We are selling garage: #{read_attribute(:ad_text)}"
  end
end
于 2013-11-02T11:44:03.877 回答