我的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,我想知道这是否可能。
谢谢大家。
1条答案
按热度按时间5anewei61#
虽然创建作用域不会通过多个级别继承,但您可以使用一个简单的
before_validation
钩子来实现这一点,该钩子从user分配1:在这里,这是可能的,因为
user
可以从Account记录中隐含。1这里我使用“assign”而不是“set”,因为对于那些使用
get_x
/set_x
模式的语言来说,“set”经常被误解为一个mutator方法。