如何在Rails表单中设置输入匹配另一模型表?实现账户下拉选择
Hey there! Let's get this account dropdown sorted for you step by step—since you're new to Rails, I'll break it down as clearly as possible.
First, we need to define the relationship between your Account and Cashbook models:
- An account can have many cashbook transactions
- Each cashbook transaction belongs to one account
Update your Account model:
# app/models/account.rb class Account < ApplicationRecord has_many :cashbooks, dependent: :destroy # Optional: Deletes related transactions if the account is removed end
Then update your Cashbook model:
# app/models/cashbook.rb class Cashbook < ApplicationRecord belongs_to :account end
account_id to Cashbooks (If Missing) Since you used scaffold to create Cashbook, it probably doesn't have an account_id field yet. Let's add that with a migration:
rails generate migration AddAccountIdToCashbooks account:references
Run the migration to apply the change to your database:
rails db:migrate
Make sure your controller allows the account_id parameter to be submitted when creating/editing a cashbook. Update the strong params in your cashbooks_controller.rb:
# app/controllers/cashbooks_controller.rb def cashbook_params # Replace `:your_existing_fields` with the actual fields from your Cashbook scaffold params.require(:cashbook).permit(:your_existing_fields, :account_id) end
Open your cashbook form partial (app/views/cashbooks/_form.html.erb) and replace any existing account_id input field with this dropdown:
<div class="field"> <%= form.label :account_id, "Select Account" %> <%= form.collection_select :account_id, Account.all, :id, :account_name, prompt: "Choose an account" %> </div>
Let me break that down:
:account_id: The form field name that maps to our cashbook's foreign keyAccount.all: The list of accounts to populate the dropdown:id: The value stored in the database when an option is selected:account_name: The visible text shown to the user in the dropdownprompt: A default placeholder option
If a user tries to create a cashbook before any accounts exist, the dropdown will be empty. You can add a check to guide them:
<div class="field"> <%= form.label :account_id, "Select Account" %> <% if Account.any? %> <%= form.collection_select :account_id, Account.all, :id, :account_name, prompt: "Choose an account" %> <% else %> <p><em>No accounts found. Please <a href="<%= new_account_path %>">create an account</a> first.</em></p> <% end %> </div>
- Go to your accounts page and create a few accounts with
account_namevalues - Navigate to the "New Cashbook" page—you should see a dropdown with all your account names!
- Select an account, submit the form, and verify the cashbook is linked correctly.
If you run into validation errors (like "Account must exist"), you can make the account association optional by updating your Cashbook model:
class Cashbook < ApplicationRecord belongs_to :account, optional: true end
内容的提问来源于stack exchange,提问作者Jean Malan

