Reputation: 1244
I am a beginner in rails, and I'm having an issue in a registration form.
I have users
and emails
in different tables (take a look) but the user registration form has an email
field mixed with all the other fields such as username and password.
At first render there's no issue, but when trying to save, if any error occurs (such as duplicated username
or email
) I follow steps here, where it says (don't redirect_to
, just do render 'new'
to keep previously inserted info. That's when it throws an error saying email
is not known.
I don't want to create the field email
in the users
table, since I already removed it from the original model. How do I fix that?
<%= form_for :user, url: users_path do |f| %>
<p>
<%= f.label :username %>
<%= f.text_field :username %>
</p>
<p>
<%= f.label :name %>
<%= f.text_field :name %>
</p>
<p>
<%= f.label :email %>
<%= f.email_field :email # Error is thrown in this line %>
</p>
<p>
<%= f.label :password %>
<%= f.password_field :password %>
</p>
<p>
<%= f.label :password_confirmation %>
<%= f.password_field :password_confirmation %>
</p>
<p>
<%= f.submit %>
</p>
def create
# render plain: params[:user].inspect
@user = User.new(user_registration_params)
if @user.save
email_params = {email: params[:user][:email], primary: true}
@email = Email.new(email_params)
@email.user = @user
if @email.save
redirect_to @user
else
@user.destroy
end
else
render 'new'
end
end
Upvotes: 0
Views: 86
Reputation: 1364
If you have connected the both models via belongs_to you can set up your form to update/create both models.
You have to declare you user with accepts_nested_attributes_for
.
See a full example here:
http://railscasts.com/episodes/196-nested-model-form-part-1
Upvotes: 1