[英]How to limit simple form association to show only current user's values
我正在 Rails 7 上使用 Ruby 构建一个费用跟踪器。我使用 pundit gem 授权每个用户只能访问他们自己的数据。 但是,当我尝试添加新交易时,它会显示所有银行账户,而不仅仅是当前用户的账户。
这就是我定义模型之间关系的方式:
class User < ApplicationRecord
has_many :accounts, dependent: :destroy
has_many :categories, dependent: :destroy
has_many :transactions, through: :accounts
end
class Account < ApplicationRecord
belongs_to :user
has_many :transactions, dependent: :destroy
enum :acc_type, [:Checking, :Savings]
enum :bank_name, [:Westpac]
end
class Transaction < ApplicationRecord
belongs_to :account
belongs_to :category
enum :tx_type, [:Debit, :Credit]
scope :ordered, -> { order(date: :desc) }
end
这是事务#new 的简单形式:
<%= simple_form_for transaction do |f| %>
<% if transaction.errors.any? %>
<div class="error-message alert alert-danger alert-dismissible fade show">
<%= transaction.errors.full_messages.to_sentence.capitalize %>
</div>
<% end %>
<%= f.input :date, as: :date, html5: true %>
<%= f.input :description %>
<%= f.input :tx_type, collection: Transaction.tx_types.keys, as: :radio_buttons, item_wrapper_class: 'form-check-inline' %>
<%= f.input :tx_amount %>
<%= f.association :account, label_method: :acc_name, value_method: :id, prompt: "Choose account" %>
<%= f.association :category, prompt: "Choose category" %>
<%= f.input :notes %>
<%= f.button :submit, class: "mt-3 btn btn-primary" %>
<% end %>
我只是想弄清楚如何以正确的方式声明此关联以获取 current_user 的帐户列表。
<%= f.association :account, label_method: :acc_name, value_method: :id, prompt: "Choose account" %>
因为,这个给了我所有的账户,而不仅仅是当前用户添加的账户。
如果有帮助,这是 GitHub 回购协议: https://github.com/jkvithanage/finance-manager
指定文档中给出的集合
https://github.com/heartcombo/simple_form#associations
f.association :account, collection: current_user.accounts, prompt: "Choose a Account"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.