英文:
Rails create/build with multiple foreign keys
问题
你想要能够仅通过帐户来创建开支,就像这个示例一样:
account = current_user.accounts.first
account.expenses.create()
# 现在会创建一个新的开支,包含以下数据:
# account_id: account.id, user_id: account.user_id
这是否可能?我找不到类似的或有用的解决方法。我只是想跳过在创建开支时传递user_id,我想知道是否可能。
英文:
i have 3 models on my Rails application:
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
I want to be able to create an expense only using the account, as in this example:
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
Is this possible?
I couldn't find anything similar or anything useful to solve this.
I just want to skip passing user_id when i create the expense and I'm wondering if it s possible.
Thank you.
答案1
得分: 0
While the creation scope won't inherit through multiple levels, you can achieve this using a simple before_validation
hook that assigns from user:
class Expense
before_validation :assign_user_from_account
protected
def assign_user_from_account
self.user ||= self.account&.user
end
end
Where here that's possible because user
can be implied from the Account record.
英文:
While the creation scope won't inherit through multiple levels, you can achieve this using a simple before_validation
hook that assigns<sup>1</sup> from user:
class Expense
before_validation :assign_user_from_account
protected
def assign_user_from_account
self.user ||= self.account&.user
end
end
Where here that's possible because user
can be implied from the Account record.
<sup>1</sup> Here I'm using "assign" instead of "set" as "set" is often misconstrued as a mutator method for those from languages that use the get_x
/set_x
pattern.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论