我有两个表users and events
,我想为我的用户分配位置(address, country, city
...),而且我的活动需要与地址国家和城市一起定位。
我应该创建一个名为location
的单独表格,其中包含两个外键user_id
和event_id
,然后添加关系user has_one location
,event has_one location
或只添加这些列(每个表(用户和事件)中的地址,国家,城市
我问这个问题,因为如果我创建一个单独的表位置,它就像用户和事件之间的连接表:location belongs_to user and location belongs_to event
,
但实际上用户和事件之间没有通过位置的关系,所以我觉得我很困惑,任何解释都会有所帮助,谢谢
答案 0 :(得分:3)
我建议创建一个单独的表location
,而不是在users
和events
表中存储地址信息,我认为polymorphic association听起来像是一个很好的关联为你的情况。
class Location < ActiveRecord::Base
belongs_to :locatable, polymorphic: true
end
class User < ActiveRecord::Base
has_many :locations, as: :locatable
end
class Event < ActiveRecord::Base
has_many :locations, as: :locatable
end
您对location
的迁移将是:
class CreateLocations < ActiveRecord::Migration
def change
create_table :locations do |t|
t.integer :locatable_id
t.string :locatable_type
...
end
end
end
答案 1 :(得分:1)
保持DRY的一般Rails范例最好通过将资源彼此分离来实现。虽然您所描述的两种方法都是可能的,但完成此操作的 Rails方式将创建一个单独的Location
模型,并从那里创建两个现有模型之间的关联。
# app/models/location.rb
class Location < ActiveRecord
has_many :users
has_many :events
attr_accessible :address, :country, :city
end
# app/models/user.rb
class User < ActiveRecord
belongs_to :location # Foreign key is location is on the User model
end
# app/models/event.rb
class Event < ActiveRecord
belongs_to :location # Foreign key to location is on the Event model
end