Rails创建/构建具有多个外键

huangapple go评论89阅读模式
英文:

Rails create/build with multiple foreign keys

问题

你想要能够仅通过帐户来创建开支,就像这个示例一样:

  1. account = current_user.accounts.first
  2. account.expenses.create()
  3. # 现在会创建一个新的开支,包含以下数据:
  4. # account_id: account.id, user_id: account.user_id

这是否可能?我找不到类似的或有用的解决方法。我只是想跳过在创建开支时传递user_id,我想知道是否可能。

英文:

i have 3 models on my Rails application:

  1. class User < ApplicationRecord
  2. has_many :accounts
  3. has_many :expenses
  4. end
  5. class Account < ApplicationRecord
  6. belongs_to :user
  7. has_many :expenses
  8. end
  9. class Expense < ApplicationRecord
  10. belongs_to :user
  11. belongs_to :account
  12. end

I want to be able to create an expense only using the account, as in this example:

  1. account = current_user.accounts.first
  2. account.expenses.create()
  3. # now a new expense is created with the following data:
  4. # 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:

  1. class Expense
  2. before_validation :assign_user_from_account
  3. protected
  4. def assign_user_from_account
  5. self.user ||= self.account&.user
  6. end
  7. 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:

  1. class Expense
  2. before_validation :assign_user_from_account
  3. protected
  4. def assign_user_from_account
  5. self.user ||= self.account&amp;.user
  6. end
  7. 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.

huangapple
  • 本文由 发表于 2023年5月10日 23:12:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76220091.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定