How to use :inverse_of with multiple associations?

冷暖自知 提交于 2019-12-13 00:08:38

问题


Does anyone know what I should put in the empty fields below to make this relationship work out of the box? I am very close to making this work as all associations work flawlessly. The only issue is that I cannot save a user with fruits attached to it as, currently, there is no :inverse_of.

I need the :inverse_of pointing in the right direction so that I can save a user with fruits instead of having to save the user first and then attach fruits to it later. Thank you!

UPDATED AFTER COMMENTS:

The User model:

class User < ApplicationRecord
  has_many :bought_fruits_users, -> { bought },
    class_name: 'FruitsUser', inverse_of: :buyer
  has_many :bought_fruits, through: :bought_fruits_users,
    class_name: 'Fruit', source: :bought_fruit

  has_many :sold_fruits_users, -> { sold },
    class_name: 'FruitsUser', inverse_of: :seller
  has_many :sold_fruits, through: :sold_fruits_users,
    class_name: 'Fruit', source: :sold_fruit
end

The middle-table model:

class FruitsUser < ApplicationRecord
  belongs_to :seller, foreign_key: :user_id,
    class_name: 'User', inverse_of: :sold_fruits_users
  belongs_to :buyer, foreign_key: :user_id,
    class_name: 'User', inverse_of: :bought_fruits_users

  belongs_to :bought_fruit, foreign_key: :fruit_id,
    class_name: 'Fruit', inverse_of: :buying_fruits_users
  belongs_to :sold_fruit, foreign_key: :fruit_id,
    class_name: 'Fruit', inverse_of: :selling_fruits_users

  scope :bought, -> { where(type_of: 'bought') }
  scope :sold, -> { where(type_of: 'sold') }
end

The Fruit model:

class Fruit < ApplicationRecord
  has_many :buying_fruits_users, -> { bought },
    class_name: 'FruitsUser', inverse_of: :bought_fruit
  has_many :buying_users, through: :bought_fruits_users,
    class_name: 'User', source: :buyer

  has_many :selling_fruits_users, -> { sold },
    class_name: 'FruitsUser', inverse_of: :sold_fruit
  has_many :selling_users, through: :sold_fruits_users,
    class_name: 'User', source: :seller
end

Still can't save it:

u = User.new                    [OK]
u.needs << Fruit.sample         [OK]
u.valid?                        [false]
u.errors                        [:bought_fruits_users=>["is invalid"]]

来源:https://stackoverflow.com/questions/40228134/how-to-use-inverse-of-with-multiple-associations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!