1

This question almost answers it, but I still think it's overkill. Trouble with Rails has_many relationships

I really just want a to do assignments like this assign

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

I've done a lot of googling around and all the information is contradictory, or explains setting up many to many relationships, and explains methods using an intermediary table. But really all the database should need is for the user table to have two differently names id fields for the locations. Will something like the following work?

User Class

  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

Location Class

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

Quite a lot of my models will need relationships like this so I would like to avoid having to create extra tables for this.

4

1 回答 1

0

您似乎正在尝试拥有两个继承位置类的表,browser_location 和 home_location,以及两个继承用户类的表,browser_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
于 2011-01-27T11:40:32.117 回答