Nested Form in Rails don't show nothing in Form - ruby-on-rails

I want to create a nested form with relations between Clientes has_many enderecos, but in my form nothing is show up.
Look my models:
class Cliente < ActiveRecord::Base
has_many :enderecos, dependent: :destroy
validates :nome, :sexo, presence: true
validates :cpf, :email, :username, presence:true, uniqueness: true
has_secure_password
accepts_nested_attributes_for :enderecos
end
And endereco:
class Endereco < ActiveRecord::Base
belongs_to :cliente
end
And my form:
<%= form_for(#cliente) do |f| %>
<div class="field">
<%= f.text_field :nome, placeholder: 'Nome completo', size: '50px' %>
</div>
<% f.fields_for :endereco do |endereco_form| %>
<div class="field">
<%= endereco_form.label :cep, 'placeholder: ' %>
<%= endereco_form.text_field :cep, placeholder: 'CEP' %>
</div>
<div class="field">
<%= endereco_form.text_field :numero, placeholder: 'Número' %>
</div>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
But inside nested part nothing is show up, what's happening?

You forgot the '=' sign:
<%= f.fields_for :endereco do |endereco_form| %>

Related

Rails 2 level nested forms

I slightly modified and extended the example for building nested forms to implement the second level of nesting. Everything is displayed perfectly on the form. Data for the person is displayed at both nesting levels correctly. The corresponding JS scripts work to add and remove nested forms. All 3 are generated using scaffold.
But when I click on update, only the main form and the first nesting level (addresses) are updated. The second nesting level (nested addresses) is not updated. Although I also get parameters from the second nesting level in the controller ("name"=>"UPDATE NAME OF NESTED ADDRESS").
{
"_method"=>"patch",
"authenticity_token"=>"VZ09CR-aO2D4Wv3AwEa5PHXo-mA_--c6QPUN6f0Gb_9SJJSL2gIwzCl4G4SbzRy2t3wxJHytBWiPwysNJMrWgg",
"person"=>{
"first_name"=>"Liz",
"last_name"=>"Smith",
"addresses_attributes"=>{
"0"=>{
"_destroy"=>"false",
"kind"=>"Some kind",
"street"=>"Some street",
"nested_addresses_attributes"=>{
"0"=>{
"_destroy"=>"false",
"name"=>"UPDATE NAME OF NESTED ADDRESS",
"id"=>"1"
}
},
"id"=>"10"}}},
"commit"=>"Update Person",
"controller"=>"people",
"action"=>"update",
"id"=>"3"}
I understand that even the first nesting level is magically handled behind the scenes, but I don't understand how? And how to handle the second level as well? In general, the Create Update, Delete methods do not work for the second nesting level.
Models
class Person < ApplicationRecord
has_many :addresses, inverse_of: :person, :dependent => :destroy
has_many :nested_addresses, through: :addresses, inverse_of: :person, :dependent => :destroy
accepts_nested_attributes_for :addresses, allow_destroy: true, reject_if: :all_blank
accepts_nested_attributes_for :nested_addresses, allow_destroy: true, reject_if: :all_blank
validates :first_name, presence: true
validates :last_name, presence: true
end
class NestedAddress < ApplicationRecord
belongs_to :address
validates :name, presence: true
end
class Address < ApplicationRecord
belongs_to :person, optional: true
has_many :nested_addresses, inverse_of: :address, :dependent => :destroy
accepts_nested_attributes_for :nested_addresses, allow_destroy: true, reject_if: :all_blank
validates :kind, presence: true
validates :street, presence: true
end
Controllers
def person_params
params.require(:person).permit(:first_name, :last_name, addresses_attributes: [:id, :kind, :street, :_destroy], nested_addresses_attributes: [:id, :name, :_destroy])
end
def address_params
params.require(:address).permit(:kind, :street, :person_id, nested_addresses_attributes: [:id, :name, :_destroy])
end
def nested_address_params
params.require(:nested_address).permit(:name, :address_id)
end
people/_form.html.erb
<%= form_with model: #person, local: true do |f| %>
<%= render "shared/validation-messages", object: #person %>
<%= f.label :first_name %>
<%= f.text_field :first_name, class: 'form-control' %>
<%= f.label :last_name %>
<%= f.text_field :last_name, class: 'form-control' %>
<br>
<fieldset>
<legend>Addresses:</legend>
<%= f.fields_for :addresses do |addresses_form| %>
<%= render "address_fields", f: addresses_form %>
<% end %>
<br>
<%= link_to_add_fields "Add Addresses", f, :addresses, 'btn btn-outline-secondary'%>
</fieldset>
<br>
<%= f.submit class: 'btn btn-success' %>
<% if params[:action] === "edit" && params[:controller] === "people" %>
<%= link_to "Delete Person", person_path(#person), method: :delete, data: { confirm: "Are You Sure?" }, class: 'btn btn-outline-danger' %>
<% end %>
<% end %>
people/_address_fields.html.erb
<div class="card nested-fields">
<div class="card-header">
<div><%= f.object.id %></div>
</div>
<div class="card-body">
<%= f.hidden_field :_destroy %>
<div>
<%= f.label :kind %>
<%= f.text_field :kind, class: 'form-control' %>
</div>
<div>
<%= f.label :street %>
<%= f.text_field :street, class: 'form-control' %>
</div>
<br>
<fieldset>
<legend>Nested addresses:</legend>
<%= f.fields_for :nested_addresses do |nested_addresses_form| %>
<%= render "nested_address_fields", f: nested_addresses_form %>
<% end %>
<br>
<%= link_to_add_fields "Add Nested Addresses", f, :nested_addresses, 'btn btn-outline-secondary btn-sm' %>
</fieldset>
<br>
<div>
<%= link_to "Remove address", '#', class: "remove_fields btn btn-outline-danger btn-sm" %>
</div>
</div>
</div>
people/_nested_address_fields.html.erb
<div class="card nested-fields">
<div class="card-body">
<%= f.hidden_field :_destroy %>
<div>
<%= f.label :name %>
<%= f.text_field :name %>
</div>
<br>
<div>
<%= link_to "Remove nested address", '#', class: "remove_fields btn btn-outline-danger btn-sm" %>
</div>
</div>
<br>
</div>
helpers/application_helper.rb
def link_to_add_fields(name, f, association, cl)
new_object = f.object.send(association).klass.new
id = new_object.object_id
fields = f.fields_for(association, new_object, child_index: id) do |builder|
render(association.to_s.singularize + "_fields", f: builder)
end
link_to(name, '#', class: 'add_fields ' + cl, data: {id: id, fields: fields.gsub("\n", "")}, role: 'button')
end
Your strong parameters permit call should reflect the actual nesting structure of parameters:
def person_params
params.require(:person).permit(
:first_name, :last_name,
addresses_attributes: [
:id, :kind, :street, :_destroy,
{ nested_addresses_attributes: [:id, :name, :_destroy] } # <= note the hash
]
)
end

Rails 5 Select Not Validating

I have an issue where a validation is suddenly not working. The field is a select box, and it's not setting the value. So when I try to submit the form, it says that Payee can't be blank. This is a 1 to 1 relationship between Expense and Payee. What happened? Do you see any issues here?
The field in question. It's in a helper but I've tried putting it back into the form with no luck.
def expense_payee_id_field(f)
f.select :payee_id, Payee.all.collect { |p| [p.display_name, p.id] }, { prompt: "Choose Payee"},{class:"fluid ui dropdown"}
end
The form:
<%= form_for #expense, html: { :class => "ui form segment" }, :remote => true do |f|%>
<div class="field">
<%= f.label :date%>
<div class="ui small input">
<%= f.date_field :date %>
</div>
</div>
<div class="field">
<%= f.label :amount %>
<div class="ui small input">
<%= f.text_field :amount %>
</div>
</div>
<div class="field">
<%= f.label :check_number %>
<div class="ui small input">
<%= f.text_field :check_number %>
</div>
</div>
<div class="field">
<%= f.label :payee %>
<div class="ui input">
<%= expense_payee_id_field(f)%>
</div>
</div>
<%= f.submit class: "ui blue button" %>
<% end %>
My models:
expense.rb
class Expense < ApplicationRecord
has_one :payee
monetize :amount_cents
has_many :expense_expense_categories, inverse_of: :expense
has_many :expense_categories, through: :expense_expense_categories, :dependent => :destroy
accepts_nested_attributes_for :expense_expense_categories,:allow_destroy => true
validates_associated :expense_expense_categories
validates :date, presence: true
validates_numericality_of :amount, presence: true, greater_than: 0
validates :expense_expense_category_ids, presence: true
validates_presence_of :payee_id
end
payee.rb
class Payee < ApplicationRecord
belongs_to :expense
validate :company_or_name
def full_name
[first_name, last_name].join(" ")
end
def display_name
if company.blank?
full_name
else
company
end
end
private
def company_or_name
if company.blank? && first_name.blank?
errors[:base] << "You must specify company or name"
end
end
end

Rails 4 nested form not saving

I have scoured all the other questions relating to this topic here, but I am still having this problem. I have a nested form inside a nested form. Answer choices are inside questions which are inside survey. I had no problem setting up the questions, and they save fine. The Answer choices, though, are not saving, and I cannot figure out where I am going wrong.
survey.rb
class Survey < ActiveRecord::Base
belongs_to :author
has_many :questions, dependent: :destroy
has_many :forms, dependent: :destroy
has_many :answer_choices, through: :question
validates :name, uniqueness: true
accepts_nested_attributes_for :questions, reject_if: proc { |attributes| attributes['text'].blank?},
allow_destroy: true
end
question.rb
class Question < ActiveRecord::Base
belongs_to :survey
has_many :responses, dependent: :destroy
has_many :answer_choices, dependent: :destroy
accepts_nested_attributes_for :answer_choices, reject_if: proc { |attributes| attributes['content'].blank?},
allow_destroy: true
end
answer_choice.rb
class AnswerChoice < ActiveRecord::Base
belongs_to :question
end
survey_controller.rb
def new
#survey = Survey.new(author_id: session[:user_id])
#survey.questions.build
#survey.questions.each { |question| 4.times { question.answer_choices.build }}
end
def edit
#survey.questions.build
#survey.questions.each { |question| 4.times { question.answer_choices.build }}
end
def survey_params
params.require(:survey).permit(:name, :description, :author_id,
questions_attributes: [:id, :text, :required, :response_type,
:_destroy, :number])
end
_form.html.erb
<%= form_for(#survey) do |f| %>
<% if #survey.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#survey.errors.count, "error") %> prohibited this survey from being saved:</h2>
<ul>
<% #survey.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :description %><br>
<%= f.text_field :description %>
</div>
<div class="field">
<%= f.hidden_field :author_id %>
</div>
<h2>Questions</h2>
<%= f.fields_for(:questions) do |ff| %>
<%= render 'questions', :f => ff %>
<% end %>
<div class="actions">
<%= f.submit 'Submit Question'%>
</div>
<div class="actions">
<%= link_to 'Finish Survey', surveys_path %>
</div>
<% end %>
_questions.html.erb
<div>
<span><%= f.index + 1 %>. </span>
<div class="field">
<%= f.hidden_field :number, value: f.index + 1 %>
</div>
<div class="field">
<%= f.label :text, "Question" %><br>
<%= f.text_field :text %>
</div>
<div class="field">
<%= f.label :response_type %><br>
<%= f.select :response_type, [["Yes/No", "yes/no"], ["Short Answer", "string"], ["Long Answer", "text"], ["Multiple Choice", "multi"]] %>
</div>
<div class="field">
<%= f.label :required %>
<%= f.check_box :required %>
</div>
<div>
<p>Answer Choices</p>
<%= f.fields_for(:answer_choices) do |ff| %>
<%= render 'answer_choices', :f => ff %>
<% end %>
</div>
<div class="field">
<%= f.label :_destroy %>
<%= f.check_box :_destroy %>
</div>
</div>
_answer_choices.html.erb
<div class="field">
<%= f.label :content %><br>
<%= f.text_field :content %>
</div>
<div class="field">
<%= f.label :_destroy %>
<%= f.check_box :_destroy %>
</div>
A few changes in your code.
Change your new method like this
def new
#survey = Survey.new(author_id: session[:user_id])
#questions = #survey.questions.build
#answer_choices = 4.times { #questions.answer_choices.build }
end
Your survey_params should look like this
def survey_params
params.require(:survey).permit(:name, :description, :author_id,
questions_attributes: [:id, :text, :required, :response_type,
:_destroy, :number, answer_choices_attributes: [:id,:content,:_destroy]])
end
And in your form code, change these lines
<%= f.fields_for(:questions) do |ff| %>
<%= f.fields_for(:answer_choices) do |ff| %>
into
<%= f.fields_for #questions do |ff| %>
<%= f.fields_for #answer_choices do |ff| %>

rails nested attribute do not show in form

I added a nested attribute to my form, the fields for the nested attribute which is Education fields do not render, the other fields do. The relationships appear to be in order and the controller does too.
Here is the code.
Controller
def new
#profile = current_user.build_student_profile
end
def profile_params
params.require(:student_profile).permit(:first_name, :last_name, :gender, student_profiles_attributes: [:degree, :university_id, :major, :major2, :start_date, :end_date, :grade, :grade_scale] )
end
Models
class Education < ActiveRecord::Base
belongs_to :student_profile
belongs_to :university
validates :grade_scale, inclusion: { in: %w(GPA4 GPA7 WAM100) }
validates :degree, :university_id, :major, :start_date, :end_date, :grade, :grade_scale, presence: true
end
class StudentProfile < ActiveRecord::Base
belongs_to :user
has_many :educations
validates :gender, inclusion: { in: %w(male female) }
validates :first_name, :last_name, :gender, presence: true
accepts_nested_attributes_for :educations
end
Form
<%= form_for (#profile) do |f| %>
<%= f.label :first_name %>
<%= f.text_field :first_name %>
<%= f.label :last_name %>
<%= f.text_field :last_name %>
<%= f.label :gender %>
<%= f.text_field :gender %>
<%= f.fields_for :educations do |education_fields| %>
<%= education_fields.label :Degree %>
<%= education_fields.text_field :degree %>
<%= education_fields.label :University %>
<%= education_fields.collection_select(:university_id, University.all, :id, :name) %>
<%= education_fields.label :Major %>
<%= education_fields.text_field :major %>
<%= education_fields.label :Additional_Major %>
<%= education_fields.text_field :major2 %>
<%= education_fields.label :Start_Date %>
<%= education_fields.date_field :start_date %>
<%= education_fields.label :End_Date %>
<%= education_fields.date_field :end_date %>
<%= education_fields.label :Grade %>
<%= education_fields.number_field :grade %>
<%= education_fields.label :Grade_Scale %>
<%= education_fields.select :grade_scale, [["GPA / 4","GPA4"], ["GPA / 7","GPA7"], ["WAM / 100","WAM100"]] %>
<% end %>
<%= f.submit :submit %>
<% end %>
I have tried to add the following to the controller new action #profile.educations.build but I get an error unknown attribute student_profile_id
Can anyone help ?
Make sure you have student_profile_id attribute/column present in educations table.
After that, as you have mentioned, you need to build educations object on student_profile as:
def new
#profile = current_user.build_student_profile
#profile.educations.build
end
Try this
<%= f.fields_for(:educations,#profile.educations.build) do |education_fields| %>
<% end %>
or
def new
#profile = current_user.build_student_profile
#educations = #profile.educations.build
end
<%= f.fields_for(#educations) do |education_fields| %>
<% end %>

Fields_for disappear when adding accepts_nested_attributes_for

I'm doing a nested form in Rails 3.2.5, but when I add the accepts_nested_attributes_for my fields_for disappear (they just stop showing in my form).
This are my models:
class Product < ActiveRecord::Base
attr_accessible :title, :description, :variants_attributes
has_many :variants
accepts_nested_attributes_for :variants
validates :title, presence: true
end
My second model is
class Variant < ActiveRecord::Base
belongs_to :product
attr_accessible :price, :sku, :weight, :inventory_quantity, :product_id
end
And in my view I have
<%= form_for [:admin, #product], :html => {:multipart => true} do |f| %>
<%= render 'admin/shared/error_messages', object: f.object %>
<fieldset>
<legend>Producto Nuevo</legend>
<div class="control-group">
<%= f.label :title, 'Título', class: 'control-label' %>
<div class="controls">
<%= f.text_field :title %>
</div>
</div>
**<%= f.fields_for :variants do |variant| %>
<%= render 'inventory_fields', f: variant %>
<% end %>**
<div class="actions">
<%= f.submit 'Guardar', class: 'btn btn-primary' %>
</div>
<% end %>
_inventory_fields.html.erb
<div class="control-group">
<%= f.label :inventory_quantity, 'How many are in stock?', class: 'control-label' %>
<div class="controls">
<%= f.text_field :inventory_quantity, class: 'span1', value: '1' %>
</div>
</div>
The part between the ** is the one that is not being printed. And when I remove accepts_nested_attributes_for in my Product model fields_for start showing again but my form won't work.
What's happening?!?!
In the controller new action call
#product.varients.build
That should create 1 in memory varient in the product varient collection and it should bind to the fields for

Resources