简体   繁体   中英

How to limit simple form association to show only current user's values

I'm building an expense tracker with Ruby on Rails 7. I used pundit gem to authorize each user to access only their own data. But still, when I try to add a new transaction, it shows all bank accounts not only current users' accounts.

This is how I defined the relationship between models:

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

This is the simple form for the transaction#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 %>

I just want to figure out how to declare this association in the right way to get a list of current_user's accounts.

<%= f.association :account, label_method: :acc_name, value_method: :id, prompt: "Choose account" %>

Because, this one gives me all the accounts, not only the ones added by the current user.

This is the GitHub repo if it is helpful: https://github.com/jkvithanage/finance-manager

Specify the collection as given in doc

https://github.com/heartcombo/simple_form#associations

f.association :account, collection: current_user.accounts, prompt: "Choose a Account"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM