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

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

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&amp;.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.

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:

确定