开发者

What's the best way to do a "couple" system in rails?

I'm programming a RPG website with Rails 3.1 and I've got a User model (fields don't matter much).

What I need is to be able to marry two users but I don't know what's the best way for the associations.

I've thought of user1 and user2 as columns but I don't know how to say that both are the same when associating it to the User model in order to know whether a User is married or not. (that's to say that a user id can be on one开发者_运维百科 column or the other one...)

Thank you in advance !


If it's always one to one you could set it up like this:

class User
  belongs_to :partner, :foreign_key => :partner_id, :class_name => 'User', :inverse_of => :partner
end

Which should handle the inverse relationship as well, e.g.

user_1.partner = user_2
user_2.partner # <user_1>

If you need Marriage as a class, the marriage could just relate to users through has_many and validate that the # of users is 2 (if it's a traditional marriage). E.g. if you went the STI route:

class Marriage < ActiveRecord::Base
  has_many :users
end

class User < ActiveRecord::Base
  belongs_to :marriage
end

class TraditionalMarriage < Marriage
  validate do |record|
    if record.users.length != 2
      record.errors.add(:users, "Marriage is between 2 people!!")
    end
  end
end

class PartyTimeMarriage < Marriage
  validate do |record|
    if record.users.length < 3
      record.errors.add(:users, "A good marriage requires at least three spouses!!")
    end
  end
end


Some form of

has_one :wife, :class_name => "User"
belongs_to :husband, :class_name => "User"

should work in your User active record model. Maybe slap on some validation for genders.

Another solution would be to create a married table with 2 User references (has_one), to hold additional data like marriage date and stuff.


this is untested, but worth experimenting with

class User < ActiveRecord::Base
    belongs_to :spouse, :class_name => "User", :foreign_key => 'spouse_id' 

    def get_married_to(user)
        self.spouse = user
        user.spouse = self
    end
end

u1 = User.new
u2 = User.new
u1.get_married_to(u2)    

also check out the rails guides: http://guides.rubyonrails.org/association_basics.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜