Rails:has_many通过关联 - 我做对了吗?

时间:2011-09-20 19:58:25

标签: ruby-on-rails ruby associations has-many-through

我使用Rails 3.1构建照片共享Web应用程序。我只想验证我的关联是否正确。

某些背景信息:User有许多ShareShare有一个User(即“ sharer ”),一个Photo和多个ReceiverReceiver是任意User

我之所以使用直通协会,只是因为我想为共享照片的每个接收者存储额外的数据。

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 < ActiveRecord::Base
  has_many :receivers
  has_many :shares, :through => :receivers
end

然后可以使用User类方法检索shares共享照片吗?

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

然后可以使用User类方法执行返回receivers收到的共享?

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

我做对了吗?

1 个答案:

答案 0 :(得分:0)

我前段时间做了类似的事情,我没有测试过这段代码,所以要玩它并看看它是否真的是你所需要的,它可能会指向你正确的方向。

如果你的工作,我没有看到改变它的意义,这个代码有点复杂,但你没有Receiver模型,一切都通过Share模型。

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