I have two models: Person
and User
. A person can have a single user or no user at all, but every user have to be belong to a person.
I have set both models like so:
Person (has a has_user attribute):
has_one :user, dependent: :destroy
accepts_nested_attributes_for :user
User (has person_id attribute):
belongs_to :person
validates_presence_of :login, :password
validates_uniqueness_of :login
In the Person form I have a nested form_for that only shows up if I check a check box that also set the has_user attribute to true on the Person's form part.
My issue is that whenever I submit a person that has no user, it still tries to validate the user. How can I make it work?
UPDATE:
In my view:
<div class="form-group">
<%= person_form.label :has_user, :class => 'inline-checkbox' do %>
Possui usuário
<%= person_form.check_box :has_user, {id: "hasUser", checked: @person.has_user} %>
<% end %>
</div>
</div>
<div id="userPart" class="findMe"
<% if @person.user.id.blank? %> style="display:none;"
<% end %>>
<h2> User: </h2>
<div class="container">
<%= person_form.fields_for :user do |user_form| %>
<%= render partial: 'users/campos_user', locals: {form: user_form} %>
<% end %>
</div>
</div>
In my Person.js:
jQuery ->
$(document).ready ->
$(document).on 'turbolinks:load', #Added line
console.log("Turbolinks ready.")
$("#hasUser").change ->
$("#userPart").toggle();
return
return
return
return
In my Person Controller:
def new
@person= Contato.new
@person.ativo = true
@page_title = 'Novo person'
@person.build_user
end
def create
@person = Person.new(person_params)
respond_to do |format|
if @person.save
flash[:notice] = 'Contato foi criado com sucesso.'
if @person.has_user == true
format.html {redirect_to controller: :users, action: :new, person_id: @person.id}
else
format.html {redirect_to @person}
end
format.json {render :show, status: :created, location: @person}
else
flash[:warn] = "Erro ao criar contato."
format.html {render :new}
format.json {render json: @person.errors, status: :unprocessable_entity}
end
end
end
Person's params:
def person_params
params.require(:person).permit(:id, :company_id,
:active, :name,
:cargo, :celular,
:email, :nascimento,
:observacoes, :mensagem_instantanea,
:tipo_msg_inst, :possui_usuario,
user_attributes: [:login, :password, :permits, :id, :person_id, :_destroy])
end