rails deeply nested form_for not able to save twice - ruby-on-rails

I have a form where teams can register for a tournament. The form saves & routes as expected when I first save the form, however if I return to the root_path & repeat the process of registering a team, the form doesn't save at all (clicking on the "Submit" button does nothing).
My feeling is that something is hanging around from the original save that is stopping a new one from happening, but I'm not able to put my finger on what it is. Code is below, hope it is sufficient.
(routes.rb)
root 'tournaments#index'
resources :tournaments do
resources :teams do
resources :players, :only => [:new, :create]
end
end
(models)
class Tournament < ApplicationRecord
has_many :teams
has_many :players, :through => :teams
accepts_nested_attributes_for :teams
accepts_nested_attributes_for :players
end
class Team < ApplicationRecord
belongs_to :tournament, required: false
has_many :players
accepts_nested_attributes_for :players
end
class Player < ApplicationRecord
belongs_to :team, required: false
has_one :tournament, :through => :team
end
(tournaments_controller.rb)
def index
#tournaments = Tournament.all
end
def show
#tournament = Tournament.find(params[:id])
end
def new
#tournament = Tournament.new
end
def create
#tournament = Tournament.new(tournament_params)
if #tournament.save
flash[:notice] = "#{#tournament.name} saved."
redirect_to root_path
else
render :new
end
end
private
def tournament_params
params.require(:tournament).permit(:name, :deadline, :divisions, :info, :payment, :tournament_date, team_attributes: [:name, :division, :contact_email, :contact_name])
end
(teams_controller.rb)
def create
#team = Team.new(team_params)
if #team.save
flash[:notice] = "Team Registered."
redirect_to tournament_team_path(params[:tournament_id], #team.id)
else
redirect_to new_tournament_team_path(params[:tournament_id])
end
end
def new
#tournament = Tournament.find_by_id(params[:tournament_id])
#team = Team.new
8.times do
#team.players.build
end
end
def show
#tournament = Tournament.find(params[:tournament_id])
#team = Team.find(params[:id])
end
private
def team_params
params.require(:team).permit(:name, :tournament_id, :division, :contact_name, :contact_email, players_attributes: [ :name, :gender, :referee ])
end
Entry link from tournaments#show page to the teams#new action (this works ... as far as that it links to the correct page)
<%= link_to(new_tournament_team_path(params[:id])) do %><div class="rounded_btn"><h3>Register Team</h3></div><% end %>
(teams/new.html.erb) - this is the form that doesn't work. I should use partials, but I'd like to get it working to start.
<main class="long_page">
<h1 class="tournament_name"><%= #tournament.name %></h1>
<h3 class="tournament_name">Team Registration</h3>
<section style="align-items: baseline;">
<div class="rounded_box">
<%= form_for [#tournament, #team] do |f| %>
<%= f.hidden_field :tournament_id, :value => #tournament.id %>
<div>
<p>
<%= f.label :division, "Division: " %>
<%= f.select :division, options_for_select([["Mixed", "mixed"], ["Mens", "mens"]]) %>
</p>
<p>
<%= f.text_field :name, required: '' %>
<label alt='Team Name' placeholder='Team Name'></label>
</p>
<p>
<%= f.text_field :contact_name, required: '' %>
<label alt='Contact Person' placeholder='Contact Person'></label>
</p>
<p>
<%= f.text_field :contact_email, required: '' %>
<label alt='Contact Email' placeholder='Contact Email'></label>
</p>
<div class="clear"></div>
</div>
<%= f.fields_for :players do |builder| %>
<div>
<%= builder.text_field :name, required: '' %>
<%= builder.select :gender, options_for_select([["Male", "male"], ["Female", "female"]]) %>
<%= builder.select :referee, options_for_select([["No", "no"], ["Yes", "yes"]]) %>
</div>
<% end %>
</div>
<div class="btn_holder">
<p>
<%= f.submit 'Submit Team', :class => 'rounded_btn' %>
</p></div>
<% end %>
</div>
</section>
This generates the following HTML output:
<body>
<container>
<header class="header" id="header">
<img alt="Taipei Touch Association Logo" src="/assets/taipei_touch_logo_faded-4bbdd185e462f4d8af3b2d25f221f27f4ae479c8adfa4701b8c3f03e9e31b36c.svg">
<span class="header_span">
<h4>Taipei Touch Association</h4>
<h3>Tournament Management System</h3>
</span>
</header>
<main class="long_page">
<h1 class="tournament_name">Dummy Tournament</h1>
<h3 class="tournament_name">Team Registration</h3>
<section style="align-items: baseline;">
<div class="rounded_box">
<form class="new_team" id="new_team" action="/tournaments/1/teams" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓"><input type="hidden" name="authenticity_token" value="+CtsL2QcMjj1703iGPpwgs8vYu7TWJfWt9jTUgCYTMaFE9JdvYIMJqdb87z4vKuDzUgb8RO96Mdvk5fW/uJUSw==">
<input value="1" type="hidden" name="team[tournament_id]" id="team_tournament_id">
<div>
<p>
<label for="team_division">Division: </label>
<select name="team[division]" id="team_division"><option value="mixed">Mixed</option>
<option value="mens">Mens</option></select>
</p>
<p>
<input required="required" type="text" name="team[name]" id="team_name">
<label alt="Team Name" placeholder="Team Name"></label>
</p>
<p>
<input required="required" type="text" name="team[contact_name]" id="team_contact_name">
<label alt="Contact Person" placeholder="Contact Person"></label>
</p>
<p>
<input required="required" type="text" name="team[contact_email]" id="team_contact_email">
<label alt="Contact Email" placeholder="Contact Email"></label>
</p>
<div class="clear"></div>
</div>
<div>
<input required="required" type="text" name="team[players_attributes][0][name]" id="team_players_attributes_0_name">
<select name="team[players_attributes][0][gender]" id="team_players_attributes_0_gender"><option value="male">Male</option>
<option value="female">Female</option></select>
<select name="team[players_attributes][0][referee]" id="team_players_attributes_0_referee"><option value="no">No</option>
<option value="yes">Yes</option></select>
</div>
<div>
<input required="required" type="text" name="team[players_attributes][1][name]" id="team_players_attributes_1_name">
<select name="team[players_attributes][1][gender]" id="team_players_attributes_1_gender"><option value="male">Male</option>
<option value="female">Female</option></select>
<select name="team[players_attributes][1][referee]" id="team_players_attributes_1_referee"><option value="no">No</option>
<option value="yes">Yes</option></select>
</div>
<div>
<input required="required" type="text" name="team[players_attributes][2][name]" id="team_players_attributes_2_name">
<select name="team[players_attributes][2][gender]" id="team_players_attributes_2_gender"><option value="male">Male</option>
<option value="female">Female</option></select>
<select name="team[players_attributes][2][referee]" id="team_players_attributes_2_referee"><option value="no">No</option>
<option value="yes">Yes</option></select>
</div>
<div>
<input required="required" type="text" name="team[players_attributes][3][name]" id="team_players_attributes_3_name">
<select name="team[players_attributes][3][gender]" id="team_players_attributes_3_gender"><option value="male">Male</option>
<option value="female">Female</option></select>
<select name="team[players_attributes][3][referee]" id="team_players_attributes_3_referee"><option value="no">No</option>
<option value="yes">Yes</option></select>
</div>
<div>
<input required="required" type="text" name="team[players_attributes][4][name]" id="team_players_attributes_4_name">
<select name="team[players_attributes][4][gender]" id="team_players_attributes_4_gender"><option value="male">Male</option>
<option value="female">Female</option></select>
<select name="team[players_attributes][4][referee]" id="team_players_attributes_4_referee"><option value="no">No</option>
<option value="yes">Yes</option></select>
</div>
<div>
<input required="required" type="text" name="team[players_attributes][5][name]" id="team_players_attributes_5_name">
<select name="team[players_attributes][5][gender]" id="team_players_attributes_5_gender"><option value="male">Male</option>
<option value="female">Female</option></select>
<select name="team[players_attributes][5][referee]" id="team_players_attributes_5_referee"><option value="no">No</option>
<option value="yes">Yes</option></select>
</div>
<div>
<input required="required" type="text" name="team[players_attributes][6][name]" id="team_players_attributes_6_name">
<select name="team[players_attributes][6][gender]" id="team_players_attributes_6_gender"><option value="male">Male</option>
<option value="female">Female</option></select>
<select name="team[players_attributes][6][referee]" id="team_players_attributes_6_referee"><option value="no">No</option>
<option value="yes">Yes</option></select>
</div>
<div>
<input required="required" type="text" name="team[players_attributes][7][name]" id="team_players_attributes_7_name">
<select name="team[players_attributes][7][gender]" id="team_players_attributes_7_gender"><option value="male">Male</option>
<option value="female">Female</option></select>
<select name="team[players_attributes][7][referee]" id="team_players_attributes_7_referee"><option value="no">No</option>
<option value="yes">Yes</option></select>
</div>
</form></div>
<div class="btn_holder">
<p>
<input type="submit" name="commit" value="Submit Team" class="rounded_btn" data-disable-with="Submit Team">
</p></div>
</section>
</main>
</container>
</body>
Note: This problem persists even when using the nested_forms gem.

I deleted <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %> from my /views/application.erb.html file & now the funtion seems to work.

Related

Rails - My 'create/new' method doesn't work

I've created a form so the user can add a new picture to the website catalog, but for some reasons it doesn't work. Once the form is filled out, I click on the 'Submit' button but nothing happens, I just stay on the same page (and I don't have any error message...).
I don't think the error comes from my Controller since nothing happens when I add the raise keyword in my Controller's 'create' method.
I'm sure this is an amateur mistake... but I can't see what it is. Thanks for your help!
picture.rb /
Picture model:
class Picture < ApplicationRecord
validates :name, presence: true
has_many_attached :photo
end
new.html.erb /
Here is my form :
<%= form_for(#picture) do |f| %>
<div class="form-group">
<%= f.label :name, "Please indicate the name" %>
<%= f.text_field :name, class:"form-control", placeholder:"(mandatory field)" %>
</div>
<div class="form-group">
<%= f.label :description, "Add a description" %>
<%= f.text_area :description, class:"form-control" %>
</div>
<div class="form-group">
<div class="row">
<div class="col">
<%= f.label :category, "Add a category" %>
<%= f.text_field :category, class:"form-control" %>
</div>
<div class="col">
<%= f.label :price, "Indicate the price (when applicable)" %>
<%= f.number_field :price, class:"form-control", placeholder:"0,00$ CAD" %>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col">
<p>Where do you want to add this item?</p>
<div>
<%= f.check_box :is_home_item %>
<%= f.label :is_home_item, "Homepage" %>
</div>
<div>
<%= f.check_box :is_portfolio_item %>
<%= f.label :is_portfolio_item, "Work" %>
</div>
<div>
<%= f.check_box :is_sketchbook_item %>
<%= f.label :is_sketchbook_item, "Sketchbook" %>
</div>
<div>
<%= f.check_box :is_shopping_item %>
<%= f.label :is_shopping_item, "Shopping" %>
</div>
</div>
<div class="col">
<div class="form-group">
<%= f.label :photo, "Select your picture" %>
<%= f.file_field :photo, class:"form-control-file" %>
</div>
</div>
</div>
</div>
<div class="form-group">
<%= f.submit class:"btn btn-lg btn-primary" %>
</div>
<% end %>
pictures_controller.rb /
class PicturesController < ApplicationController
def new
#picture = Picture.new
end
def create
#picture = Picture.new(picture_params)
if #picture.save
redirect_to root_path(#picture), notice: "Picture was successfully created"
else
render :new
end
end
private
def picture_params
params.require(:picture).permit(:name, :description, :category, :price, :is_home_item, :is_portfolio_item, :is_sketchbook_item, :is_shopping_item, :photo)
end
end
And here is the text I got on my local server console
Here is the HTML output of my form :
<form>
<input type="hidden" name="authenticity_token" value="7MxWbzbltjXcAx2dvgRwIu07WMpyjPQji6LI6ELifMZODLJyMBucNApnPRk8vsjshSEjyMMenDUfvDw6pN+/4Q==">
<div class="form-group">
<label for="picture_name">Indicate the name</label>
<input class="form-control" placeholder="(mandatory field)" type="text" name="picture[name]" id="picture_name">
</div>
<div class="form-group">
<label for="picture_description">Add a description</label>
<textarea class="form-control" name="picture[description]" id="picture_description"></textarea>
</div>
<div class="form-group">
<div class="row">
<div class="col">
<label for="picture_category">Add a category</label>
<input class="form-control" type="text" name="picture[category]" id="picture_category">
</div>
<div class="col">
<label for="picture_price">Indicate the price (when applicable)</label>
<input class="form-control" placeholder="0,00$ CAD" type="number" name="picture[price]" id="picture_price">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col">
<p>Where do you want to add your picture?</p>
<div>
<input name="picture[is_home_item]" type="hidden" value="0"><input type="checkbox" value="1" name="picture[is_home_item]" id="picture_is_home_item">
<label for="picture_is_home_item">Homepage</label>
</div>
<div>
<input name="picture[is_portfolio_item]" type="hidden" value="0"><input type="checkbox" value="1" name="picture[is_portfolio_item]" id="picture_is_portfolio_item">
<label for="picture_is_portfolio_item">Work</label>
</div>
<div>
<input name="picture[is_sketchbook_item]" type="hidden" value="0"><input type="checkbox" value="1" name="picture[is_sketchbook_item]" id="picture_is_sketchbook_item">
<label for="picture_is_sketchbook_item">Sketchbook</label>
</div>
<div>
<input name="picture[is_shopping_item]" type="hidden" value="0"><input type="checkbox" value="1" name="picture[is_shopping_item]" id="picture_is_shopping_item">
<label for="picture_is_shopping_item">Shopping</label>
</div>
</div>
<div class="col">
<div class="form-group">
<label for="picture_photo">Select your picture</label>
<input class="form-control-file" type="file" name="picture[photo]" id="picture_photo">
</div>
</div>
</div>
</div>
<div class="form-group">
<input type="submit" name="commit" value="Create Picture" class="btn btn-lg btn-primary" data-disable-with="Create Picture">
</div>
My routes :
Rails.application.routes.draw do
devise_for :users
# Pages routes
root to: 'pages#home'
get 'about', to: 'pages#about'
get 'portfolio', to: 'pages#portfolio'
get 'sketchbook', to: 'pages#sketchbook'
get 'shopping', to: 'pages#shopping'
# Pictures routes
resources :pictures
end
And these are my routes in the Terminal
Not quite sure why this is happening, but form_for is deprecated, so you should replace it with form_with.
You can use a model, such as your #picture with form_with as described in the docs.
<%= form_with(model: #picture) do |form| %>
# fields
<% end %>
This should create a form DOM object that looks like this:
<form action="/pictures" method="post" accept-charset="UTF-8" >
<input name="authenticity_token" type="hidden" value="..." />
...
</form>
If for some reason it doesn't, you can always pass a method: :post in the form_with (ie. <%= form_with(model: #picture, method: :post) do |form| %>).
Currently, you have got has_many_attached with a singular photo. That does not seem to be the right syntax. Have you tried changing to has_many_attached :photos and modifying the picture_params to have photos passed as an array photos: []?
Or if you wanted to attach one photo, then you should try changing to has_one_attached :photo in the Picture model.

Rails 5 partial form not showing in production but is in development

Here's the relevant code. This all works on my development server with a direct code copy to the production server. Development works fine. I don't do much with html or css so it could be there. Anyone see something obvious? I've checked suggestions from other similar questions in the forums but I'm not seeing it.
Code from exams controller:
def new
#exam = Exam.new
#exam.questions.build if #exam.questions.blank?
end
# GET /exams/1/edit
def edit
end
# POST /exams
# POST /exams.json
def create
#exam = Exam.new(exam_params)
respond_to do |format|
if #exam.save
format.html { redirect_to #exam, notice: 'Exam was successfully created.' }
format.json { render :show, status: :created, location: #exam }
else
format.html { render :new }
format.json { render json: #exam.errors, status: :unprocessable_entity }
end
end
end
_form
<%= form_for(#exam) do |f| %>
<% if #exam.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(exam.errors.count, "error") %> prohibited this exam from being saved:</h2>
<ul>
<% #exam.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %>:
<%= f.text_field :title,:size =>"50" %>
</div>
<div class="field">
<%= f.check_box :pcredit %>
<%= f.label :pcredit, "Give partial credit when a question has multiple correct answers." %>
</div>
<div class="field">
<%= f.check_box :available %>
<%= f.label :available, "Available to take" %>
</div>
<% exam.user_id = current_user.id %>
<div class="field">
<%= f.hidden_field :user_id, value: current_user.id %>
</div>
<div class="field">
<%= f.hidden_field :department_id, value: current_user.department_id %>
</div>
<div class="field">
<%= f.hidden_field :creator_id, value: current_user.id %>
</div>
<div class="field">
<%= f.check_box :retake %>
<%= f.label :retake, "Retakes allowed" %>
</div>
<div class="field">
<%= f.check_box :results %>
<%= f.label :results, "Show results" %>
</div>
<hr>
<div id="questions">
<%= f.fields_for :questions do |question| %>
<%= render 'question_fields', f: question %>
<hr>
<% end %>
<%= link_to_add_association 'add_question', f, :questions, partial: 'question_fields' %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Questions Partial
<strong>Question:</strong>
<div class='nested-fields'>
<div class="field">
<%= f.label :name, "Question:" %>
<%= f.text_area :name,:size =>"50" %>
</div>
<div class="field">
<%= f.label :value, "Point Value:" %>
<%= f.number_field :value %>
</div>
<div class="field">
<%= f.label :available %>
<%= f.check_box :available %>
</div>
<%= link_to_remove_association "remove question", f %>
<div>
<p><strong>Answers:</strong></p>
<div id="answers">
<%= f.fields_for :answers do |answer| %>
<%= render 'answer_fields', f: answer %>
<% end %>
</div>
<%= link_to_add_association 'add_answer', f, :answers, partial: 'answer_fields' %>
<hr>
</div>
</div>
Answers Partial
<div class="field">
<%= f.label :name, "Answer:" %>
<%= f.text_area :name,:size =>"50" %>
</div>
<div class="field">
<%= f.label :correct %>
<%= f.check_box :correct %>
</div>
<div class="field">
<%= f.hidden_field :creator_id, value: current_user.id %>
</div>
<div class="field">
<%= f.hidden_field :department_id, value: current_user.department_id %>
</div>
<div class="field">
<%= f.label :locked %>
<%= f.check_box :locked %><br>
<%= link_to_remove_association "remove answer", f %>
</div>
Page Source:
<!DOCTYPE html>
<html>
<head>
<title>Online Placements</title>
<link rel="stylesheet" media="all" href="/assets/exams-72737ac2bb269793edd945e3daa76d03d1bc74588f32b4acceb48ba3328ddc14.css" />
<script src="/assets/application-3199215ebdb5afca46347c9bb159d59b78620065cea4336725d6fdeebc9e0e12.js"></script>
<meta name="csrf-param" content="authenticity_token" />
<meta name="csrf-token" content="+r+/jvc85b8QgSkJrpoT/idGMB3vYnkfLePBCjnWdsGBP1xhb/L86UA80toVa+/SXxGzb1KhDR0mm8hLkGt+Fw==" />
</head>
<body id="exams">
<div id="banner">
<img src=/assets/KHSlogo-3f9139495681edc2572d84a2d1157e33990d56e4536f98c1addaf5e9c092b2fc.gif width="160" height="77" alt="*****" />
<title1>**************</title1>
<p id="notice"></p>
</div>
<div id="columns">
<div id="side">
<font color="#ff0000">Home</font><br>
Placements
<br>
<hr>
<font color="#ff0000">Admins Only</font><br>
Users
<br>
<hr>
<font color="#ff0000">Documentation</font>
<br><a target="_blank" href="https://docs.google.com/document/d/11_WLL7wZIkzssubus4XAQcouKkpRdrG6Lu-dWGn7gJY/edit#bookmark=id.8glqcm3gxwmz">User Document</a>
<br><a target="_blank" href="https://docs.google.com/document/d/11_WLL7wZIkzssubus4XAQcouKkpRdrG6Lu-dWGn7gJY/edit#bookmark=id.o7htlx2i1tyx">Placement Help</a>
</div>
<div id="main">
<li>
Logged in as <b>****- </b>
<a rel="nofollow" data-method="delete" href="/users/sign_out">Logout</a>
</li>
<h1>Editing Exam: Placement Test</h1>
<form class="edit_exam" id="edit_exam_1" action="/exams/1" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓" /><input type="hidden" name="_method" value="patch" /><input type="hidden" name="authenticity_token" value="K98vKBkYaUZL5WOt5xjlopkOVk7pvhc3HgBp5M0zmsQu3Hy2oBN5AzZjI3gTYcghP9qhXrpqAQenrZnYcVNw5Q==" />
<div class="field">
<label for="exam_title">Title</label>:
<input size="50" type="text" value="Placement Test" name="exam[title]" id="exam_title" />
</div>
<div class="field">
<input name="exam[pcredit]" type="hidden" value="0" /><input type="checkbox" value="1" checked="checked" name="exam[pcredit]" id="exam_pcredit" />
<label for="exam_pcredit">Give partial credit when a question has multiple correct answers.</label>
</div>
<div class="field">
<input name="exam[available]" type="hidden" value="0" /><input type="checkbox" value="1" checked="checked" name="exam[available]" id="exam_available" />
<label for="exam_available">Available to take</label>
</div>
<div class="field">
<input value="1" type="hidden" name="exam[user_id]" id="exam_user_id" />
</div>
<div class="field">
<input value="1" type="hidden" name="exam[department_id]" id="exam_department_id" />
</div>
<div class="field">
<input value="1" type="hidden" name="exam[creator_id]" id="exam_creator_id" />
</div>
<div class="field">
<input name="exam[retake]" type="hidden" value="0" /><input type="checkbox" value="1" checked="checked" name="exam[retake]" id="exam_retake" />
<label for="exam_retake">Retakes allowed</label>
</div>
<div class="field">
<input name="exam[results]" type="hidden" value="0" /><input type="checkbox" value="1" checked="checked" name="exam[results]" id="exam_results" />
<label for="exam_results">Show results</label>
</div>
<hr>
<div id="questions">
<a class="add_fields" data-association="question" data-associations="questions" data-association-insertion-template="<strong>Question:</strong>
<div class='nested-fields'>
<div class="field">
<label for="exam_questions_attributes_new_questions_name">Question:</label>
<textarea name="exam[questions_attributes][new_questions][name]" id="exam_questions_attributes_new_questions_name" cols="50">
</textarea>
</div>
<div class="field">
<label for="exam_questions_attributes_new_questions_value">Point Value:</label>
<input type="number" name="exam[questions_attributes][new_questions][value]" id="exam_questions_attributes_new_questions_value" />
</div>
<div class="field">
<label for="exam_questions_attributes_new_questions_available">Available</label>
<input name="exam[questions_attributes][new_questions][available]" type="hidden" value="0" /><input type="checkbox" value="1" name="exam[questions_attributes][new_questions][available]" id="exam_questions_attributes_new_questions_available" />
</div>
<input type="hidden" name="exam[questions_attributes][new_questions][_destroy]" id="exam_questions_attributes_new_questions__destroy" value="false" /><a class="remove_fields dynamic" href="#">remove question</a>
<div>
<p><strong>Answers:</strong></p>
<div id="answers">
</div>
<a class="add_fields" data-association="answer" data-associations="answers" data-association-insertion-template=" &lt;div class=&quot;field&quot;&gt;
&lt;label for=&quot;exam_questions_attributes_new_questions_answers_attributes_new_answers_name&quot;&gt;Answer:&lt;/label&gt;
&lt;textarea name=&quot;exam[questions_attributes][new_questions][answers_attributes][new_answers][name]&quot; id=&quot;exam_questions_attributes_new_questions_answers_attributes_new_answers_name&quot; cols=&quot;50&quot;&gt;
&lt;/textarea&gt;
&lt;/div&gt;
&lt;div class=&quot;field&quot;&gt;
&lt;label for=&quot;exam_questions_attributes_new_questions_answers_attributes_new_answers_correct&quot;&gt;Correct&lt;/label&gt;
&lt;input name=&quot;exam[questions_attributes][new_questions][answers_attributes][new_answers][correct]&quot; type=&quot;hidden&quot; value=&quot;0&quot; /&gt;&lt;input type=&quot;checkbox&quot; value=&quot;1&quot; name=&quot;exam[questions_attributes][new_questions][answers_attributes][new_answers][correct]&quot; id=&quot;exam_questions_attributes_new_questions_answers_attributes_new_answers_correct&quot; /&gt;
&lt;/div&gt;
&lt;div class=&quot;field&quot;&gt;
&lt;input value=&quot;1&quot; type=&quot;hidden&quot; name=&quot;exam[questions_attributes][new_questions][answers_attributes][new_answers][creator_id]&quot; id=&quot;exam_questions_attributes_new_questions_answers_attributes_new_answers_creator_id&quot; /&gt;
&lt;/div&gt;
&lt;div class=&quot;field&quot;&gt;
&lt;input value=&quot;1&quot; type=&quot;hidden&quot; name=&quot;exam[questions_attributes][new_questions][answers_attributes][new_answers][department_id]&quot; id=&quot;exam_questions_attributes_new_questions_answers_attributes_new_answers_department_id&quot; /&gt;
&lt;/div&gt;
&lt;div class=&quot;field&quot;&gt;
&lt;label for=&quot;exam_questions_attributes_new_questions_answers_attributes_new_answers_locked&quot;&gt;Locked&lt;/label&gt;
&lt;input name=&quot;exam[questions_attributes][new_questions][answers_attributes][new_answers][locked]&quot; type=&quot;hidden&quot; value=&quot;0&quot; /&gt;&lt;input type=&quot;checkbox&quot; value=&quot;1&quot; name=&quot;exam[questions_attributes][new_questions][answers_attributes][new_answers][locked]&quot; id=&quot;exam_questions_attributes_new_questions_answers_attributes_new_answers_locked&quot; /&gt;&lt;br&gt;
&lt;input type=&quot;hidden&quot; name=&quot;exam[questions_attributes][new_questions][answers_attributes][new_answers][_destroy]&quot; id=&quot;exam_questions_attributes_new_questions_answers_attributes_new_answers__destroy&quot; value=&quot;false&quot; /&gt;&lt;a class=&quot;remove_fields dynamic&quot; href=&quot;#&quot;&gt;remove answer&lt;/a&gt;
&lt;/div&gt;
" href="#">add_answer</a>
<hr>
</div>
</div>
" href="#">add_question</a>
</div>
<div class="actions">
<input type="submit" name="commit" value="Update Exam" data-disable-with="Update Exam" />
</div>
</form>
Show |
Back
<br><br><br>
</div>
</div>
</body>
</html>
It would be great to see controller part for it where #exam is defined
I assume that in your prod case (where form doesn't show) association questions is empty.
So there are several variants:
1.In controller always build a question if the association is empty
#exam.questions.build if #exam.questions.blank?
2.You can add entity in the view
f.fields_for :questions, #exam.questions.presence || [#exam.questions.build] do |question|
3.Take into account such case in view and show proper message
<% if #exam.questions.present? %>
<%= render 'questions_part' %>
<% else %>
<%= render 'no_questions_partial' %>
<% end %>
I think 1 variant is better.
OK I finally figured it out. I had to precompile assets. Working now.
Thanks to those who offered suggestions. I really appreciate your time.

Nested form accepts_nested_attributes_for giving dynamic Array - Rails4

I am working on Rails4 with Nested form, accepts_nested_attributes_for i can able to generate the nested form but its giving dynamic array the the form when i inspect the form.
<input type="text" name="event_venue[event_contact_details_attributes][1403763304978][name]" id="event_venue_event_contact_details_attributes_1403763304978_name" class="form-control">
But it should be,
<input type="text" name="event_venue[event_contact_details_attributes][1][name]" id="event_venue_event_contact_details_attributes_1_name" class="form-control">
<div class="formWrapper">
<div class="col-md-6">
<div class="form-group">
<label for="exampleInputEmail1">Name</label>
<input type="text" name="event_venue[event_contact_details_attributes][1403764358820][name]" id="event_venue_event_contact_details_attributes_1403764358820_name" class="form-control">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Phone</label>
<input type="text" name="event_venue[event_contact_details_attributes][1403764358820][telephone]" id="event_venue_event_contact_details_attributes_1403764358820_telephone" class="form-control">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email</label>
<input type="text" name="event_venue[event_contact_details_attributes][1403764358820][email]" id="event_venue_event_contact_details_attributes_1403764358820_email" class="form-control">
</div>
<div class="clearfix"></div>
<input type="hidden" value="false" name="event_venue[event_contact_details_attributes][1403764358820][_destroy]" id="event_venue_event_contact_details_attributes_1403764358820__destroy"><a onclick="remove_fields(this); return false;" href="#">remove</a>
</div>
</div>
Can you help me out where i am missing the things...!!!
In first nested form set it's coming right,
<div class="formWrapper">
<div class="col-md-6">
<div class="form-group">
<label for="exampleInputEmail1">Name</label>
<input type="text" value="AS" name="event_venue[event_contact_details_attributes][0][name]" id="event_venue_event_contact_details_attributes_0_name" class="form-control">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Phone</label>
<input type="text" value="AS" name="event_venue[event_contact_details_attributes][0][telephone]" id="event_venue_event_contact_details_attributes_0_telephone" class="form-control">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email</label>
<input type="text" value="AS" name="event_venue[event_contact_details_attributes][0][email]" id="event_venue_event_contact_details_attributes_0_email" class="form-control">
</div>
<div class="clearfix"></div>
<input type="hidden" value="false" name="event_venue[event_contact_details_attributes][0][_destroy]" id="event_venue_event_contact_details_attributes_0__destroy"><a onclick="remove_fields(this); return false;" href="#">remove</a>
</div>
</div>
Event Venue Model,
has_many :event_contact_details, :dependent => :destroy
accepts_nested_attributes_for :event_contact_details, allow_destroy: true
Controller,
def new
#event_venue = EventVenue.new
#event_venue.event_contact_details.build
end
form,
<%= f.fields_for :event_contact_details do |builder| %>
<%= render :partial => 'event_venues/event_contact_detail_fields',
:locals => { :f => builder } %>
<% end %>
<p><%= link_to_add_fields "Add More", f, :event_contact_details %></p>

How do I create an interactive form with Simple Form?

I have a model (Listing) that has many, many attributes (say 25).
I would like to create an AJAX form that is dynamic based on the input in the form.
Meaning that if a user chooses type=b, they will see other fields that they should see and not ones they shouldn't.
Ideally they should load immediately, with the right content from the db - i.e. in an AJAXy way.
What's the best way to approach this?
Thanks.
Edit: Here is an example of my _form.html.erb. You will notice that I have included 2 if statements that indicate which fields should show if the property_type value chosen is one of those specified:
<%= simple_form_for(#listing) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :headline %>
<%= f.input :price %>
<%= f.association :property_type %>
If property_type == "coop"
<%= f.input :maintenance %>
<%= f.input :coop_deductible %>
<%= f.input :flip_tax %>
if property_type == "condo"
<%= f.input :common_charges %>
<%= f.input :taxes %>
</div>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
Edit 2:
This is the Rails form helper that I used - powered by the gem Simple_Form:
<%= simple_form_for #listing, :defaults => { :wrapper_html => { :class => 'form-horizontal' } } do |f| %>
<%= f.error_notification %>
<fieldset>
<%= f.association :listing_category, :label => "Category: ", :label_html => { :class => "control-label"}, :wrapper_html => { :class => "controls"} %>
<div style="display: none;" data-show-for="Exclusive">
<%= f.association :listing_type %>
<%= f.association :user %>
<%= f.association :boro %>
</div>
<div style="display: none;" data-show-for="Open">
<%= f.association :neighborhood %>
<%= f.association :building %>
<%= f.association :term %>
<%= f.association :property_type %>
</div>
<div class="form-actions">
<%= f.button :submit, :class => "btn btn-primary" %>
<!-- <button type="submit" class="btn btn-primary">Save and Continue</button>
<button type="reset" class="btn">Cancel</button> -->
</div>
</fieldset>
<% end %>
This is the HTML it produced:
<form accept-charset="UTF-8" action="/listings" class="simple_form new_listing" id="new_listing" method="post" novalidate="novalidate"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="1oDfg41Wx/SiPCsvf4qTAcxhFUGSNlhlLfkMy8nHW1E=" /></div>
<fieldset>
<div class="control-group select optional controls"><label class="select optional control-label control-label" for="listing_listing_category_id">Category:</label><div class="controls"><select class="select optional" id="listing_listing_category_id" name="listing[listing_category_id]"><option value=""></option>
<option value="1">Exclusive</option>
<option value="2">Open</option></select></div></div>
<div style="display: none;" data-show-for="Exclusive">
<div class="control-group select optional form-horizontal"><label class="select optional control-label" for="listing_listing_type_id">Listing type</label><div class="controls"><select class="select optional" id="listing_listing_type_id" name="listing[listing_type_id]"><option value=""></option>
</select></div></div>
<div class="control-group select optional form-horizontal"><label class="select optional control-label" for="listing_user_id">User</label><div class="controls"><select class="select optional" id="listing_user_id" name="listing[user_id]"><option value=""></option>
<option value="1">First User</option>
<option value="2">Second User</option>
<option value="3">Third User</option>
<option value="4">Fourth User</option>
<option value="5">Fifth User</option></select></div></div>
<div class="control-group select optional form-horizontal"><label class="select optional control-label" for="listing_boro_id">Boro</label><div class="controls"><select class="select optional" id="listing_boro_id" name="listing[boro_id]"><option value=""></option>
<option value="1">Brooklyn</option></select></div></div>
</div>
<div style="display: none;" data-show-for="Open">
<div class="control-group select optional form-horizontal"><label class="select optional control-label" for="listing_neighborhood_id">Neighborhood</label><div class="controls"><select class="select optional" id="listing_neighborhood_id" name="listing[neighborhood_id]"><option value=""></option>
<option value="1">Prospect Heights</option></select></div></div>
<div class="control-group select optional form-horizontal"><label class="select optional control-label" for="listing_building_id">Building</label><div class="controls"><select class="select optional" id="listing_building_id" name="listing[building_id]"><option value=""></option>
<option value="1">Trump Towers</option></select></div></div>
<div class="control-group select optional form-horizontal"><label class="select optional control-label" for="listing_term_id">Term</label><div class="controls"><select class="select optional" id="listing_term_id" name="listing[term_id]"><option value=""></option>
</select></div></div>
<div class="control-group select optional form-horizontal"><label class="select optional control-label" for="listing_property_type_id">Property type</label><div class="controls"><select class="select optional" id="listing_property_type_id" name="listing[property_type_id]"><option value=""></option>
<option value="1">Coop</option></select></div></div>
</div>
<div class="form-actions">
<input class="btn btn btn-primary" name="commit" type="submit" value="Create Listing" />
<!-- <button type="submit" class="btn btn-primary">Save and Continue</button>
<button type="reset" class="btn">Cancel</button> -->
</div>
</fieldset>
</form>
This is the JS that I included in my listing.js - which corresponds to the file that this form is on app/views/listings/new.html.erb
$(document).ready(function({
$('#listing_listing_category_id').on('change', function(){
var option = $(this).find(':selected');
$('[data-show-for]').hide(); //And maybe reset?
$('[data-show-for="+ option.text +"]').show()
});
});
When I chose the option I want, it doesn't show me the fields I want to see.
Personally I wouldn't use AJAX, just straight JS/JQuery to show/hide on click using data attributes.
See fiddle: http://jsfiddle.net/XnPZF/
First, add the data attributes to the sections you want to hide/show:
<div style="display: none;" data-show-for="coop">
<%= f.input :maintenance %>
<%= f.input :coop_deductible %>
<%= f.input :flip_tax %>
</div>
<div style="display: none;" data-show-for="condo">
<%= f.input :common_charges %>
<%= f.input :taxes %>
</div>
Then create a change event on the select:
$('#listing_property_type').on('change', function(){
var option = $(this).find(':selected');
$('[data-show-for]').hide(); //And maybe reset?
$('[data-show-for='+ option.text() +']').show()
});
For data-show-for, you can use Option text or value, just be sure to make sure the event knows which. If you plan to use this a lot of times, you could generalize it, but that would mean building your options.

Rails form_for html being set to display: none

I have a standard rails form_for tag for creating and editing a new hotel. This renders just fine when visited via the edit_hotels_path, however when visting the new_hotels_path the html form tag is being set to display: none; causing the form to not show only in the "new" view.
I have restarted the server, emptied the cache, made sure they are using the same CSS but it still renders with display set to none.
Here are the styles as seen using developer tools
<form accept-charset="UTF-8" action="/hotels" class="new_hotel" id="new_hotel" method="post" style="display: none; "><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓"><input name="authenticity_token" type="hidden" value="pDlR3gV2tm+Z7xRFdC0uclNY13FlzxUSOjOrHs2ttO0="></div>
element.style {
display: none;
}
below is the html source being rendered, which doesn't include display: none;
<form accept-charset="UTF-8" action="/hotels" class="new_hotel" id="new_hotel" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="authenticity_token" type="hidden" value="pDlR3gV2tm+Z7xRFdC0uclNY13FlzxUSOjOrHs2ttO0=" /></div>
<div class="control-group">
<div class="controls">
<input id="hotel_name" name="hotel[name]" placeholder="Name..." size="30" type="text" /><br>
<select id="hotel_year" name="hotel[year]"><option value="2012">2012</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
<option value="2015">2015</option></select><br>
<select id="hotel_month" name="hotel[month]"><option value="January">January</option>
<option value="February">February</option>
<option value="March">March</option>
<option value="April">April</option>
<option value="May">May</option>
<option value="June">June</option>
<option value="July">July</option>
<option value="August">August</option>
<option value="September">September</option>
<option value="October">October</option>
<option value="November">November</option>
<option value="December">December</option></select><br>
<textarea cols="40" id="hotel_body" name="hotel[body]" placeholder="Hotel info up to 1000 words..." rows="20">
</textarea><br>
<input id="hotel_meta_tags" name="hotel[meta_tags]" placeholder="Enter meta tags for image, as a comma separated list..." size="30" type="text" /><br>
<legend>Winner</legend>
<input name="hotel[winner]" type="hidden" value="0" /><input id="hotel_winner" name="hotel[winner]" type="checkbox" value="1" />
<br/>
</div>
<div class="form-actions">
<input class="btn-large btn-success" name="commit" type="submit" value="create" />
</div>
</div>
</form>
below is the code, would appreciated any help.
_form.html.erb
<%= form_for #hotel do |f| %>
<% if #hotel.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#hotel.errors.count, "error") %> prohibited this article from being saved:</h2>
<ul>
<% #hotel.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<%= render partial: "shared/code_sheet" %>
<div class="control-group">
<div class="controls">
<%= f.text_field :name, placeholder: "Name..." %><br>
<%= f.select :year, [2012, 2013, 2014, 2015] %><br>
<%= f.select :month, ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] %><br>
<%= f.text_area :body, placeholder: "Hotel info up to 1000 words..." %><br>
<%= f.text_field :meta_tags, placeholder: "Enter meta tags for image, as a comma separated list..." %><br>
<legend>Winner</legend>
<%= f.check_box :winner %>
<br/>
</div>
<div class="form-actions">
<%= f.submit "create", class: "btn-large btn-success" %>
</div>
</div>
<% end %>
edit.html.erb
<div class="container">
<h1>Editing hotel</h1>
<%= render "form" %>
<%= link_to 'hotels index', hotels_path %>
</div>
new.html.erb
<div class="container">
<h1>New hotel</h1>
<%= render "form" %>
<%= link_to 'hotels index', hotels_path %>
</div>
It could be anything. You must know what is in your CSS. Did you search for 'display: none;' in your CSS files and checked the matches? element.style is usually set directly on the HTML tag. Search the view also place debugging string to make sure it is pulling the appropriate .html.

Resources