我知道那里有很多类似的问题,但是我无法找到符合我特殊情况的任何问题,坦率地说,我的大脑正在把自己捆绑成试图围绕这种情况的结。因此,非常感谢任何外部见解!
我有Users
和Portfolios
。 Portfolios
有一个creator
,User
。 这很好。
但Portfolios
之间也可以共享Users
。我使用has_many_through
自引用关系对此进行建模。 这是我遇到麻烦的地方。
我的分享模式: /app/models/share.rb
class Share < ActiveRecord::Base
belongs_to :shared_by, class_name: 'User' # the user who shared the portfolio
belongs_to :shared_with, class_name: 'User' # the user who was shared with
belongs_to :portfolio # the portfolio being shared
end
数据库中的“我的共享”表格(取自schema.rb
)
create_table "shares", force: true do |t|
t.text "message"
t.integer "portfolio_id" # the id of the portfolio shared
t.integer "shared_by_id" # the id of the sharer (user)
t.integer "shared_with_id" # the id of the person shared with (user)
t.datetime "created_at"
t.datetime "updated_at"
end
我的用户模型: /app/models/user.rb
class User < ActiveRecord::Base
has_many :created_portfolios, foreign_key: 'creator_id', class_name: 'Portfolio'
has_many :shares_by_me, foreign_key: 'shared_by', class_name: 'Share'
has_many :shared_with_me, foreign_key: 'shared_with', class_name: 'Share'
# portfolios the user has shared
has_many :shared_portfolios, through: :shares_by_me, source: :portfolio, class_name: 'Portfolio'
# portfolios that have been shared with the user
has_many :portfolios_shared_with, through: :shared_with_me, source: :portfolio, class_name: 'Portfolio'
...
end
我的投资组合模型: /app/models/portfolio.rb
class Portfolio < ActiveRecord::Base
has_many :shares
# users this portfolio has been shared with
has_many :shared_with, through: :shares, foreign_key: 'shared_with_id', class_name: 'User'
# users that have shared this portfolio
has_many :shared_by, through: :shares, foreign_key: 'shared_by_id', class_name: 'User'
# the creator of the portfolio
belongs_to :creator, class_name: 'User'
end
任何帮助将不胜感激!我有点疯了!
答案 0 :(得分:0)
糟糕。
我几乎拥有它。我的user.rb
文件中只有一个小错误:
而不是:
has_many :shares_by_me, foreign_key: 'shared_by', class_name: 'Share'
我需要:
has_many :shares_by_me, foreign_key: 'shared_by_id', class_name: 'Share'
对这么一件小事太多头疼了!但我猜这总是如此:)