ruby Rails使用多个外键创建/构建

3zwjbxry  于 2023-05-17  发布在  Ruby
关注(0)|答案(1)|浏览(152)

我的Rails应用程序中有3个模型:

class User < ApplicationRecord
  has_many :accounts
  has_many :expenses
end

class Account < ApplicationRecord
  belongs_to :user
  has_many :expenses

end
class Expense < ApplicationRecord
  belongs_to :user
  belongs_to :account
end

我希望能够仅使用帐户创建费用,如下例所示:

account = current_user.accounts.first
account.expenses.create()
# now a new expense is created with the following data:
# account_id: account.id, user_id: account.user_id

这可能吗?我找不到任何类似的或有用的东西来解决这个问题。
我只是想在创建费用时跳过传递user_id,我想知道这是否可能。
谢谢大家。

5anewei6

5anewei61#

虽然创建作用域不会通过多个级别继承,但您可以使用一个简单的before_validation钩子来实现这一点,该钩子从user分配1:

class Expense
  before_validation :assign_user_from_account

protected
  def assign_user_from_account
    self.user ||= self.account&.user
  end
end

在这里,这是可能的,因为user可以从Account记录中隐含。
1这里我使用“assign”而不是“set”,因为对于那些使用get_x/set_x模式的语言来说,“set”经常被误解为一个mutator方法。

相关问题