开发者

Rails: has_many through association - did I get this right?

I building a photo sharing web application using Rails 3.1. I just want to verify that I got the associations right.

Some context: A User has many Share. A Share has one User (i.e the "sharer"), one Photoand many Receiver. A Receiveris a arbitrary User.

The reason why I'm using a through association is simply because I want to store additional data for each receiver of the shared photo.

class Photo < ActiveRecord::Base
  has_many :shares
end

class Receiver < ActiveRecord::Base
  belongs_to :share
  belongs_to :user
end

class Share < ActiveRecord::Base
  belongs_to :photo
  belongs_to :user
  has_many :receivers
  has_many :users, :through => :receivers
end

class User < Ac开发者_开发百科tiveRecord::Base
  has_many :receivers
  has_many :shares, :through => :receivers
end

Retreiving a User shared photos could then be performed using the shares class method?

User.first.shares
# => [<#Share:0x000>, ...]

Retreiving a User received shares could then be performed using the receivers class method?

User.first.receivers
# => [<#Receiver:0x000>, ...]

Did I get this right?


I did something similar a while ago, I didn't test this code, so play around with it and see if it actually is what you need, it may point you in the right direction though.

If yours work I don't see the point of changing it, this code is a bit more complex but you dont have a Receiver model, everything goes through the Share model.

class User < ActiveRecord::Base
  has_many :shares_links, :class_name => "Share", :foreign_key => :sharing_id, :dependent => :destroy
  has_many :receiver_links, :class_name => "Share", :foreign_key => :shared_to_id, :dependent => :destroy

  has_many :shares, :through => :shares_links
  has_many :receivers, :through => :receiver_links
end

class Share < ActiveRecord::Base
  belongs_to :sharing, :validate => true, :class_name => "User", :foreign_key => :sharing_id 
  belongs_to :shared_to, :validate => true, :class_name => "User", :foreign_key => :shared_to_id

  has_one :photo
end

class Photo < ActiveRecord::Base
  belongs_to :photo
end

User.first.shares
User.first.receivers
User.first.receivers.first.photo
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜