在Rails 5中通过Account模型结合Devise创建用户的问题
Hey there! Let's troubleshoot this nested form issue step by step—this is a super common gotcha when setting up account + owner creation flows. Here are the most critical fixes to get your form working smoothly:
First, make sure your Account and User models are properly linked and set up to handle nested form data:
- In
app/models/account.rb:class Account < ApplicationRecord has_one :owner, class_name: "User", dependent: :destroy accepts_nested_attributes_for :owner # This is mandatory to accept owner params via the account form end - In
app/models/user.rb:class User < ApplicationRecord belongs_to :account end
If you don't build the associated owner for your @account instance, the fields_for block won't render correctly, and you'll get errors on submission. Update your AccountsController#new action:
def new @account = Account.new @account.build_owner # This creates an empty User instance tied to the account end
f.fields_for Instead of Bare fields_for) Your current form uses fields_for :owner directly, but it needs to be scoped to the form_for builder to link to the @account object. Adjust your ERB like this:
<%= form_for @account do |f| %> <!-- Add your subdomain field here first --> <p> <%= f.label :subdomain %> <%= f.text_field :subdomain %> </p> <!-- Scope fields_for to the form builder --> <%= f.fields_for :owner do |o| %> <p> <%= o.label :f_name %> <%= o.text_field :f_name %> </p> <p> <%= o.label :m_name %> <%= o.text_field :m_name %> </p> <!-- Add other owner fields (last name, email, password, etc.) here --> <% end %> <%= f.submit "Create Account & Owner" %> <% end %>
You need to explicitly permit the owner_attributes hash in your account_params method, otherwise Rails will reject the owner data:
def account_params params.require(:account).permit( :subdomain, owner_attributes: [:f_name, :m_name, :l_name, :email, :password, :password_confirmation] ) end
If you're still hitting errors after these steps, share the specific exception message (like "param is missing" or "undefined method for nil:NilClass") and we can dig deeper!
内容的提问来源于stack exchange,提问作者Shawn Wilson

