在rails中创建多个一对多关系

时间:2011-01-04 12:58:21

标签: ruby-on-rails activerecord has-many belongs-to

这个问题几乎可以解决它,但我仍然觉得它太过分了。 Trouble with Rails has_many relationships

我真的只想做一个像这样的作业

@user.browsing_location = location1
@user.home_location = location2

我做了大量的谷歌搜索,所有的信息都是矛盾的,或解释了建立多对多的关系,并解释了使用中间表的方法。但实际上所有数据库应该需要的是用户表具有两个不同名称的位置id字段。会有类似以下的工作吗?

用户类

  class User < ActiveRecord::Base
  #locations created by this user
  has_many :locations, :foreign_key => :creator_id

  #locations for browsing and visiting
  belongs_to :browsing_location, :source => :location
  belongs_to :home_location, :source => :location

end

位置等级

class Location < ActiveRecord::Base
  #Users who are just browsing this location now
  has_many :browsing_users, :foreign_key => :browsing_location_id, :source => :users
  #Users who are living here now
  has_many :home_users, :foreign_key => :home_location_id, :source => :users

  #User who created this location
  has_one :user
end

我的很多模型都需要这样的关系,所以我想避免为此创建额外的表格。

1 个答案:

答案 0 :(得分:0)

您似乎正在尝试拥有两个继承位置类的表,browse_location和home_location以及两个继承用户类的表,browse_user和home_user。对于Rails 3:

你有一般的想法,但看起来你有点混淆了。 :source用于多对多关系以确定要使用的关联。您似乎需要的是:class_name

我需要查看用户和位置的表定义,以确保正确使用:foreign_key属性。

user.rb

class User < ActiveRecord::Base
  # locations created by this user
  has_many :locations, :foreign_key => :creator_id

  # I'm assuming the locations belong to the user, as you're end goal was stated as  
  # the ability to call set user.browsing_location and user.home_location 
  # that would mean that browsing_location and home_location would need to belong to
  # the User class, not the other way around.  
  has_many :browsing_locations, :class_name => :location
  has_many :home_locations, :class_name => :location

end

class Location < ActiveRecord::Base

  # User who created the location
  belongs_to :user

  # Users who are just browsing this location now
  has_many :browsing_users, :class_name => :users
  # Users who are living here now
  has_many :home_users, :class_name => :users

end
相关问题