I have two models, User
and Account
Accounts
model validates presence of name and organization User
model validates presence of email and password I have one form for account creation which combines the two models: accountname and organization from Account
, email and password from User
.
How do I validate both models while creating an account?
You can absolutely validate both models, the below should get you started but lookup any commands you don't recognise to get further help.
First link your models and allow nested attributes with validations for the child:
class User < ActiveRecord::Base
has_one :account
accepts_nested_attributes_for :account
validates_associated :account
end
class Account < ActiveRecord::Base
belongs_to :user
end
Now use a fields_for
helper to define your form:
<% form_for @user do |form| %>
<%= form.input :email %>
<% form.fields_for :account do |account_fields| %>
<%= account_fields.input :organization %>
<% end %>
<%= form.submit %>
<% end %>
Now in your controller when you update the attributes of @user the account attributes will automatically be updated with the account params. Then when the parent is validated, so will the children be.
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.