Flash messages (ajax) - ruby-on-rails

Is it possible to show the errors of the form in the flash messages in ajax? I want to show the errors of the form when is not possible to save a record due to unique field.
my index
<!--<p id="notice"><%= notice %></p>-->
<h1>Empresas</h1>
<style>
.container {
}
</style>
<div class="container">
<div class="row">
<div class="text-center">
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#mynewempresa">
Nueva empresa
</button>
</div>
</div>
<br>
<br>
<table id="empresas" class="display"><!--el id empresas es de datatables referenciado en empresas.coffe y display class es una clase de datatables-->
<thead>
<tr><!--active es para sombrear la fila-->
<th>Clave</th>
<th>Empresa</th>
<th>Acción</th>
<th></th>
</tr>
</thead>
<tbody id="container_empresas">
<%= render #empresas %><!--carga todos los empresas-->
</tbody>
</table>
<!-- Modal create action -->
<%= form_for(#empresa, remote: true, html: {class: "form-horizontal formulario-validado-create"}) do |f| %> <!--ajax remote: true-->
<div class="modal fade" id="mynewempresa" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Agregar empresa</h4>
</div>
<div class="modal-body">
<div id="flash_messages_placeholder" >
</div>
<div class="form-group">
<%= f.label :IdEmpresa, "Clave:", class: "control-label col-md-2 " %>
<div class="col-md-3">
<%= f.text_field :IdEmpresa, class: "form-control empresa_clave",autofocus: true, minlength: "1", required: "true" %>
</div>
<%= f.label :Empresa, "Empresa:", class: "control-label col-md-2" %>
<div class="col-md-5">
<%= f.text_field :Empresa, class: "form-control empresa_empresa",minlength: "4", required: "true" %>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" id="mynewempresaclose">Cerrar</button>
<%= submit_tag "Crear", class: "btn btn-primary"%>
</div>
</div>
</div>
</div>
<%end%>
</div>
my controller
class EmpresasController < ApplicationController
before_action :set_empresa, only: [:show, :edit, :update, :destroy]
before_action :authenticate_usuario!
# GET /empresas
# GET /empresas.json
def index
#empresas = Empresa.all
#empresa = Empresa.new
respond_to do |format|
format.html
format.csv { send_data #empresas.to_csv}
format.xls #{ send_data #empresas.to_csv(col_sep: "\t") }
end
end
def import
Empresa.import(params[:file])
redirect_to empresas_path, notice: "Sucursales importadas."
end
# GET /empresas/1
# GET /empresas/1.json
def show
end
# GET /empresas/new
def new
#empresa = Empresa.new
end
# GET /empresas/1/edit
def edit
end
# POST /empresas
# POST /empresas.json
def create
#empresa = Empresa.new(empresa_params)
format.js { render 'shared/error_messages_js'}
respond_to do |format|
if #empresa.save
format.html { redirect_to #empresa, notice: 'Empresa was successfully created.' }
format.json { render :show, status: :created, location: #empresa }
format.js {flash.now[:notice] = 'La Sucursal se ha creado de forma exitosa.'} #ajax
else
format.html { render :new }
format.json { render json: #empresa.errors, status: :unprocessable_entity }
format.js {flash.now[:alert] = 'Error al crear la sucursal.'} #ajax
end
end
end
# PATCH/PUT /empresas/1
# PATCH/PUT /empresas/1.json
def update
respond_to do |format|
##use locals if multiple models
##add model errors
flash.now[:error] = #empresa.errors.full_messages
##flash.now[:error] = #model.errors.full_messages.to_sentence
if #empresa.update(empresa_params)
format.html { redirect_to #empresa, notice: 'Empresa was successfully updated.' }
format.json { render :show, status: :ok, location: #empresa }
format.js {flash.now[:notice] = 'La Sucursal se ha actualizado de forma exitosa.'} #ajax
else
format.html { render :edit }
format.json { render json: #empresa.errors, status: :unprocessable_entity }
format.js {flash.now[:alert] = 'Error al actualizar la sucursal.'} #ajax
end
end
end
# DELETE /empresas/1
# DELETE /empresas/1.json
def destroy
#empresa.destroy
respond_to do |format|
format.html { redirect_to empresas_url, notice: 'Empresa was successfully destroyed.' }
format.json { head :no_content }
format.js {flash.now[:notice] = 'La Sucursal se ha borrado de forma exitosa.'} #ajax
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_empresa
#empresa = Empresa.find(params[:idempresa])
end
# Never trust parameters from the scary internet, only allow the white list through.
def empresa_params
params.require(:empresa).permit(:IdEmpresa, :Empresa)
end
end
my application helper:
module ApplicationHelper
###application_helper.rb
def flash_display
Rails.logger.info "show flash message ajax======== "
response = ""
flash.each do |name, msg|
msg=msg ###"<i class='fa fa-quote-left fa-border'></i>"+msg+"<i class='fa fa-quote-right fa-border'></i>"+"<button type='button' class='close' title='hide' data-dismiss='alert'><i class='fa-times-circle-o fa pull-right'></i></button>".html_safe
response = response +
content_tag(:div, msg, :id => "flash_#{name}",:class=>"alert alert-danger") do
"#{msg}".html_safe
end
end
flash.discard
response
end
end
##views/shared/error_messages_js.erb
$('#flash_messages_placeholder').html("<%= escape_javascript raw(flash_display) %>");

Yes..its possible..
firstly,create a helper method that can be used to show flash messages on the view.
###application_helper.rb
def flash_display
Rails.logger.info "show flash message ajax======== "
response = ""
flash.each do |name, msg|
msg=msg ###"<i class='fa fa-quote-left fa-border'></i>"+msg+"<i class='fa fa-quote-right fa-border'></i>"+"<button type='button' class='close' title='hide' data-dismiss='alert'><i class='fa-times-circle-o fa pull-right'></i></button>".html_safe
response = response +
content_tag(:div, msg, :id => "flash_#{name}",:class=>"alert alert-danger") do
"#{msg}".html_safe
end
end
flash.discard
response
end
Secondly,In your controller code where you post data using remote=true,handle js response as shown below.
respond_to do |format|
##use locals if multiple models
##add model errors
##flash.now[:error] = #model.errors.full_messages
##flash.now[:error] = #model.errors.full_messages.to_sentence
flash.now[:error]="You cannot edit this Page"
format.js { render 'shared/error_messages_js'}
end
##views/shared/error_messages_js.erb
$('#flash_messages_placeholder').html("<%= escape_javascript raw(flash_display) %>");
So,the above js.erb file will look for an empty placeholder to show flash messages.So your form must also have a placeholder
###_form.html.erb
<form action="<%= post_data_path(current_user)%>" method="post" data-remote="true">
<div id="flash_messages_placeholder" > </div>
##input fields/submit button goes here
<%end%>
Hope it helps :)

Related

Nil location provided. Can't build URI error with project tasks turbo stream

I have a projects model that has many tasks. You can click a checkbox to complete the task and what I am trying to have happen is when that happens change the style of the task and return some additional information. The task updates fine and completes, but errors out on the form and checkbox stating "Nil location provided. Can't build URI " when trying to return the turbo stream. Also when creating new tasks I get the same error. Any thoughts on why in both cases it is triggering that error?
Task.html.erb:
<div class="table-row" id="<%= dom_id task %>" data-id="<%= task.id %>">
<div class="table-cell px-6 py-4 whitespace-nowrap text-md font-medium text-gray-800 dark:text-gray-200"><%= form_with(model: [#project, #task]) do |form| %><%= form.check_box :completed,
data: {
id: task.id,
action: "tasks#toggle"
},checked: task.completed,
class: "w-4 h-4 border-gray-300 rounded bg-gray-50 focus:ring-3 focus:ring-primary-300 dark:focus:ring-primary-600 dark:ring-offset-gray-800 dark:bg-gray-700 dark:border-gray-600" %><% end %>
</div>
<div class="table-cell px-6 py-4 whitespace-nowrap text-md text-gray-800 dark:text-gray-200">
<div class="text-base font-semibold text-gray-900 dark:text-white"><%= task.description %>
</div>
<div class="text-sm font-normal text-gray-500 dark:text-gray-400"><% if task.completed? %>
<div class="text-base font-normal text-gray-500 dark:text-gray-400">Completed: <%= time_ago_in_words(task.updated_at) %> ago
</span> by
<span class="font-weight-normal ml-2"><%= task.user.email %>
</div><% end %>
</div>
</div>
<div class="table-cell px-6 py-4 whitespace-nowrap text-right text-md font-medium">
<div class="flex justify-end">
<button type="button" data-modal-toggle="product-modal" class="inline-flex items-center px-3 py-2 text-sm font-medium text-center text-white bg-primary-700 rounded-lg hover:bg-primary-800 focus:ring-4 focus:ring-primary-300 dark:bg-primary-600 dark:hover:bg-primary-700 dark:focus:ring-primary-800">
<svg class="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 20 20"
xmlns="http://www.w3.org/2000/svg">
<path d="M17.414 2.586a2 2 0 00-2.828 0L7 10.172V13h2.828l7.586-7.586a2 2 0 000-2.828z"></path>
<path fill-rule="evenodd" d="M2 6a2 2 0 012-2h4a1 1 0 010 2H4v10h10v-4a1 1 0 112 0v4a2 2 0 01-2 2H4a2 2 0 01-2-2V6z" clip-rule="evenodd"></path>
</svg>
Edit item
</button>
<button type="button" data-modal-toggle="delete-product-modal" class="inline-flex items-center px-3 py-2 text-sm font-medium text-center text-white bg-red-700 rounded-lg hover:bg-red-800 focus:ring-4 focus:ring-red-300 dark:focus:ring-red-900">
<svg class="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 20 20"
xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z" clip-rule="evenodd"></path>
</svg>
Delete item
</button>
</div>
</div>
Within project/show:
<%= turbo_stream_from "tasks" %>
<div class="overflow-hidden">
<div class="table border-collapse table-auto w-full divide-y divide-gray-200 dark:divide-gray-700">
<div class="table-row-group divide-y divide-gray-200 bg-white dark:divide-gray-700 dark:bg-gray-800"
id="tasks" data-controller="drag" data-drag-url="/projects/<%= #project.id %>/tasks/:id/move">
<%= render #tasks.order('position asc') %>
</div>
</div>
</div>
Task.rb
class Task < ApplicationRecord
belongs_to :project
belongs_to :user
acts_as_list
after_create_commit {broadcast_prepend_to "tasks"}
end
Tasks controller:
class TasksController < ApplicationController
before_action :set_task, except: [:create]
before_action :set_project, except: [:toggle]
# GET /tasks or /tasks.json
def index
#tasks = Task.all
#task = Task.new
end
# GET /tasks/1 or /tasks/1.json
def show
end
# GET /tasks/new
def new
#task = Task.new
end
# GET /tasks/1/edit
def edit
end
# POST /tasks or /tasks.json
def create
#task = #project.tasks.build(task_params)
#task.user_id = current_user.id
respond_to do |format|
if #task.save
format.turbo_stream
format.html { redirect_to project_task_path(#project, #task), notice: "Task was successfully created." }
format.json { render :show, status: :created, location: #task }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: #task.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /tasks/1 or /tasks/1.json
def update
respond_to do |format|
if #task.update(task_params)
format.html { redirect_to project_task_path(#project, #task), notice: "Task was successfully updated." }
format.json { render :show, status: :ok, location: #task }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: #task.errors, status: :unprocessable_entity }
end
end
end
# DELETE /tasks/1 or /tasks/1.json
def destroy
#task.destroy
respond_to do |format|
format.html { redirect_to tasks_url, notice: "Task was successfully destroyed." }
format.json { head :no_content }
end
end
def toggle
#task = Task.find(params[:id])
#task.update(completed: params[:completed])
end
def move
#task.insert_at(params[:position].to_i)
head :ok
end
private
# Use callbacks to share common setup or constraints between actions.
def set_task
#task = Task.find(params[:id])
end
def set_project
#project = Project.find(params[:project_id])
end
# Only allow a list of trusted parameters through.
def task_params
params.require(:task).permit(:title, :position, :description, :project_id, :user_id, :status, :completed)
end
end
I have two issues here. One issue affecting the creation of tasks that broadcast prepend, and trying to broadcast a replace via a checkbox check.
I fixed the prepend issue on create. I had another section of the projects/show page with id="tasks" that was causing the problem. I am going to pursue the checkbox issue separately.

How to render a modal after failed update in Rails 5.2?

I use a modal window to edit a schedule from the schedules index. Each schedule provides a link to the edit method:
<%= link_to edit_scheduler_production_schedule_path(schedule),
title: t('.Edit'),
data: { toggle: "modal", target: "#childModal" },
class: "mat-icon-button mat-button-base mat-secondary" do %>
<span class="fa fa-edit"></span>
<% end %>
The edit method from ProductionSchedulesController is quite simple:
# GET /production_schedules/1/edit
def edit
render layout: false
end
So is the edit.html.erb file:
<% provide :childModalTitle do %>
<%= t('.Edit') %>
<% end %>
<%= render 'form' %>
And the edit form is quite light too:
<%= form_with model: [namespace, #production_job, #production_schedule], html: {id: "edit_form"} do |f| %>
<div class="modal-header">
<h5 class="modal-title" id="editScheduleModalLabel">
<%= t('scheduler.production_schedules.edit.Edit') %>
</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<%= render partial: "shared/error_list", locals: { errors: #production_schedule.errors } %>
<section class="tabbable" id="schedule_information">
---
</section>
</div>
<div class="modal-footer">
<button type="button" class="mat-stroked-button mat-button-base" data-dismiss="modal">
<%= t('Cancel') %>
</button>
<button class="mat-flat-button mat-button-base mat-primary">
<%= t('Submit') %>
</button>
</div>
<% end %>
The update method is the place where I get frustrated:
# PATCH/PUT /production_schedules/1 or /production_schedules/1.json
def update
#production_job = ProductionJob.find(#production_schedule.production_job_id)
Rails.logger.interactions.info "Schedule update - id: #{#production_schedule.id},
code: #{#production_schedule.code},
mode: #{#production_schedule.mode.code}"
if #production_schedule.mode.code == 'TEST' or #production_schedule.mode.code == 'MESSAGE'
#production_schedule.next_run = nil
end
respond_to do |format|
if #production_schedule.update(production_schedule_params)
json_parameters_serialization(#production_schedule)
#production_schedule.update_attribute(:status_id, statuses.find { |x| x["code"] == "READY" }.id || 0)
format.html { redirect_to scheduler_production_job_path(#production_job), notice: "Production schedule was successfully updated." }
format.json { render :show, status: :ok, location: #production_schedule }
else
#production_schedule.update_attribute(:status_id, statuses.find { |x| x["code"] == "INACTIVE" }.id || 0)
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: #production_schedule.errors, status: :unprocessable_entity }
end
end
end
If the update fails, edit view is rendered, but not in a modal.
How can I re-render this form in a modal when the update method rejects the update?
Thanks a lot!
In Rails 6.0 and 5.2, all forms using form_with implement remote: true by default. These forms will submit data using an XHR (Ajax) request. So, you need to respond to the request in the same format.
Update modal body of edit_form (Wrapping error messages in div)
<div class="modal-body">
<div id="errorList">
<%= render partial: "shared/error_list", locals: { errors: #production_schedule.errors } %>
</div>
</div>
Add update.js.erb
<% if (!#production_schedule.errors.present?) %>
window.location.reload(); # To refresh the page.
<% else %> # To render error messages in modal when update failed.
$("#errorList").html('<%= escape_javascript( render(partial: "shared/error_list", locals: { errors: #production_schedule.errors) ) %>');
<% end %>

Undefined method `errors' for nil:NilClass - when I click on Form Submit

I have added validation to the form FORM. So whenever I click on the create employee with all the details it works but when I do not put the values I get this error. I have even changed to #employee in form_with.
I just want validations to be seen. How do I handle this?
Employees Controller:
class EmployeesController < ApplicationController
before_action :set_employee, only: %i[ show edit update destroy]
# GET /employees or /employees.json
def index
#employees = Employee.all
end
# GET /employees/1 or /employees/1.json
def show
end
# GET /employees/new
def new
#employee = Employee.new
end
# GET /employees/1/edit
def edit
end
# POST /employees or /employees.json
def create
employee_service = EmployeeCreationService.new(employee_params)
respond_to do |format|
if employee_service.execute!
format.html { redirect_to employee_service.employee}
# format.json { render :show, status: :created, location: #employee }
else
format.html { render :new, status: :unprocessable_entity }
# format.json { render json: #employee.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /employees/1 or /employees/1.json
def update
respond_to do |format|
if #employee.update(employee_params)
format.html { redirect_to #employee}
# format.json { render :show, status: :ok, location: #employee }
else
format.html { render :edit, status: :unprocessable_entity }
# format.json { render json: #employee.errors, status: :unprocessable_entity }
end
end
end
# DELETE /employees/1 or /employees/1.json
def destroy
#employee.destroy
respond_to do |format|
format.html { redirect_to employees_url}
# format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_employee
#employee = Employee.find(params[:id])
end
# Only allow a list of trusted parameters through.
def employee_params
params.require(:employee).permit(:name, :phone, :designation_id, :email, :password)
end
end
Form:
<%= form_with(model: employee, local: true) do |form| %>
<% if employee.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(employee.errors.count, "error") %> prohibited this employee from being saved:</h2>
<ul>
<% employee.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="form-group row">
<%= form.label :name,class:"col-sm-2 col-form-label" %>
<div class="col-sm-10">
<%= form.text_field :name %>
</div>
</div>
<div class="form-group row">
<%= form.label :phone,class:"col-sm-2 col-form-label" %>
<div class="col-sm-10">
<%= form.text_field :phone %>
</div>
</div>
<div class="form-group row">
<%= form.label :designation_id,class:"col-sm-2 col-form-label" %>
<div class="col-sm-10">
<%= form.select :designation_id, [["SOFTWARE ENGINEER", "2"], ["SERVICE ENGINEER", "3"]] %>
</div>
</div>
<div class="form-group row">
<%= form.label :Email,class:"col-sm-2 col-form-label" %>
<div class="col-sm-10">
<%= email_field_tag 'employee[email]' %>
</div>
</div>
<div class="form-group row">
<%= form.label :Password,class:"col-sm-2 col-form-label" %>
<div class="col-sm-10">
<%= password_field_tag 'employee[password]' %>
</div>
</div>
<br />
<div class='form-group'>
<div class="align-left">
<h5 align="left">
<%= form.submit class:"btn btn-dark"%>
</h5></button>
</div>
<div class="align">
<div >
<%= link_to 'Go Back', employees_path , class:"btn btn-primary btn-sm"%>
</div>
</div>
</div>
<% end %>
Service - to create employee and User simultaneously(Using Devise):
class EmployeeCreationService
attr_reader :employee
def initialize(employee_params)
#employee_params = employee_params.except(:email, :password)
#user_params = employee_params.slice(:email, :password)
end
def execute!
begin
#employee = Employee.create!(#employee_params)
User.create!(#user_params.merge(employee: employee))
rescue => exception
#ex = exception
return false
end
true
end
end
I suppose the problem in the create action in else branch of condition:
The form needs that #employee variable should be set but it isn't for this case.
You need to have the ability to have an instance of the Employee class from your service. Something like this:
#employee = employee_service.execute!
if #employee.valid?
redirect_to
else
render
def create
#employee = Employee.new(employee_valid)
employee_service = EmployeeCreationService.new(employee_params)
respond_to do |format|
if employee_service.execute!
format.html { redirect_to employee_service.employee}
else
format.html { render :new, status: :unprocessable_entity }
end
end
end
Made these changes and it works fine now. For the validations, I have added JS.
Also slice employeee params with only the name phone and designation.

Rails Want to Display Object#Show inside a modal without loading application template

Instead of showing a table in my index page with links to each object's show path, I want to have each object as a bootstrap modal where it will render the show view inside the modal. When I click on the modal, it displays the entire application.html.erb template inside the modal instead of the show view of the object. Is there a way to just display the object's show view, while still staying on the index page and not yielding the entire application template.
index.html.erb
<p id="notice"><%= notice %></p>
<h1>Buildings</h1>
<table class="table table-striped">
<thead>
<tr>
<th>County</th>
...
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% #buildings.each do |building| %>
<tr>
<td><%= link_to 'Show', building %></td>
<td><%= link_to 'Edit', edit_building_path(building) %></td>
<td><%= link_to 'Destroy', building, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<div class="text-center">
<%= link_to "#{building.development_name}", building, class: 'btn btn-primary', data: {toggle:'modal', target: '#myModal'} %>
</div>
</tbody>
</table>
<br>
<div class="modal inmodal" id="myModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content animated bounceInRight">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<i class="fa fa-laptop modal-icon"></i>
<h4 class="modal-title"><%= building.development_name %></h4>
<small class="font-bold">Lorem Ipsum is simply dummy text of the printing and typesetting industry.</small>
</div>
<div class="modal-body">
...
<div class="form-group"><label>Sample Input</label> <input type="email" placeholder="Enter your email" class="form-control"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-white" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<% end %>
buildings_controller.rb
class BuildingsController < ApplicationController
before_action :set_building, only: [:show, :edit, :update, :destroy]
# GET /buildings
# GET /buildings.json
def index
#buildings = Building.where(user_id: current_user)
end
# GET /buildings/1
# GET /buildings/1.json
def show
end
# GET /buildings/new
def new
#building = Building.new
end
# GET /buildings/1/edit
def edit
end
# POST /buildings
# POST /buildings.json
def create
#building = Building.new(building_params)
respond_to do |format|
if #building.save
session[:building_id] = #building.id
redirect_to listing_wizards_path
format.html { redirect_to #building, notice: 'Building was successfully created.' }
format.json { render :show, status: :created, location: #building }
else
format.html { render :new }
format.json { render json: #building.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /buildings/1
# PATCH/PUT /buildings/1.json
def update
respond_to do |format|
if #building.update(building_params)
format.html { redirect_to #building, notice: 'Building was successfully updated.' }
format.json { render :show, status: :ok, location: #building }
else
format.html { render :edit }
format.json { render json: #building.errors, status: :unprocessable_entity }
end
end
end
# DELETE /buildings/1
# DELETE /buildings/1.json
def destroy
#building.destroy
respond_to do |format|
format.html { redirect_to buildings_url, notice: 'Building was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_building
#building = Building.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def building_params
params.require(:building).permit(:list_type, :county, :area, :city, :folio, :street, :compass_point, :street_name, :state, :zip, :zip4, :unit, :legal, :zoning, :geographical, :municip_code, :township, :section, :subdivision, :parcel, :map_coordinates, :elementary_school, :middle_school, :senior_high_school, :subdivision_name, :development_name, :model_name_in_mls, :user_id, additional_room_ids: [], amenity_ids: [], approval_ids: [], construction_ids: [], cooling_description_ids: [], design_ids: [], dining_area_ids: [], equipment_ids: [], exterior_feature_ids: [], floor_ids: [], heat_ids: [], interior_feature_ids: [], leasing_term_ids: [], lot_description_ids: [], misc_ids: [], parking_restriction_ids: [], pet_restriction_ids: [], pool_description_ids: [], rental_dep_incl_ids: [], rental_pay_inc_ids: [], rental_restriction_ids: [], security_ids: [], showing_instruction_ids: [], water_access_ids: [], waterfront_desc_ids: [], window_treatment_ids: [])
end
end
You can pass the layout option when rendering your show method
You can also tell Rails to render with no layout at all:
render layout: false
If you'd like to still render the layout if they type the show url into the browser you can do
render layout: !request.xhr?
Just stick that in your show action and rails will still render the show view and then you can take the response in your Ajax call and put it into your modal.

undefined method `hirahana_value' for nil:NilClass

I try to understand what my buddy has coded to call in a show#view some instance variable. I have a problem to understand his code and call the method hirahana_value.
Here is my controller
class SymbolesController < ApplicationController
before_action :set_symbole, only: [:show, :edit, :update, :destroy, :load_form, :load_attributes_form]
def index
#symboles = Symbole.all
end
def show
end
def new
#symbole = Symbole.new
end
def edit
end
def create
#symbole = Symbole.new()
if symbole_params[:symbole_type].present?
#symbole.build_kanji_attribute if symbole_params[:symbole_type] == "kanji"
#symbole.build_hiragana_and_katagana_attribute if symbole_params[:symbole_type] == "hiragana_and_katagana"
end
#symbole.assign_attributes(symbole_params)
respond_to do |format|
if #symbole.save
format.html { redirect_to #symbole, notice: 'Symbole was successfully created.' }
format.json { render :show, status: :created, location: #symbole }
else
format.html { render :new }
format.json { render json: #symbole.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #symbole.update(symbole_params)
format.html { redirect_to #symbole, notice: 'Symbole was successfully updated.' }
format.json { render :show, status: :ok, location: #symbole }
else
format.html { render :edit }
format.json { render json: #symbole.errors, status: :unprocessable_entity }
end
end
end
def destroy
#symbole.destroy
respond_to do |format|
format.html { redirect_to symboles_url, notice: 'Symbole was successfully destroyed.' }
format.json { head :no_content }
end
end
def load_form
#symbole = Symbole.new if #symbole.nil?
if params[:form_name].present?
respond_to do |format|
format.js { render "ajax_form_"+params[:form_name] }
end
end
end
def load_attributes_form
#symbole = Symbole.new if #symbole.nil?
if params[:form_name].present?
respond_to do |format|
format.js { render "ajax_form_"+params[:form_name] }
end
end
end
private
def set_symbole
if params[:id].present?
#symbole = Symbole.find(params[:id])
else
#symbole = Symbole.new
end
end
def symbole_params
params.require(:symbole).permit(:lang, :example_fr, :symbole_type, :css_class, kanji_attribute_attributes: [:value,:concept, :fr],
hiragana_and_katagana_attribute_attributes: [:hirahana_value,:katagana_value, :fr]
)
end
end
And here is the new#view to create my object
<%= simple_form_for #symbole, :defaults => {:required => true} do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.hidden_field :lang, value: "Japonais"%>
<%= f.select :symbole_type, options_for_select([["Kanji", "kanji"], ["Hiragana/Katagana", "hiragana_and_katagana"]]) , {:prompt => "Type de symbole", selected: #symbole.symbole_type}, {required: true} %>
<div id="specific_attributes">
</div>
<%= f.input :example_fr, placeholder: "Exemple", label: "Exemple" %>
<%= f.input :css_class, placeholder: "Nom de la classe css" , label: "Classe"%>
</div>
<div class="form-actions">
<%= f.button :submit, "Valider" %>
</div>
<% end %>
here is the show#view, I just want to call
<ul class="list-inline text-center card-frame">
<li>
<div class="card">
<div class="front">
<!-- PARAMETRER LE RESPONSIVE BOOTSTRAP -->
<!-- <div class="col-sm- col-xs-4 col-md-3"> -->
<div class="card-hiragana hiragana-<%=#hiragana_and_katagana_attributes.hirahana_value.downcase.last%>">
<h1><b><%= #hiragana_and_katagana_attributes.hirahana_value %></b></h1>
</div>
<div class="card-katakana">
<p><%= #hiragana_and_katagana_attributes.hirahana_value %></p>
</div>
<!-- </div> -->
</div>
<div class="back">
<div class="col-sm-3 col-xs-4 col-md-3 containerbackcards-<%=#hiragana_and_katagana_attributes.hirahana_value.downcase.last%>">
<div class="backcard-hiragana">
<h1><b><%= #hiragana_and_katagana_attributes.hirahana_value %></b></h1>
</div>
<div class="card-bigletter">
<p><%= #hiragana_and_katagana_attributes.hirahana_value %></p>
</div>
</div>
</div>
</div>
</li>
</ul>
<div class="text-center buttons-view-post">
<% if current_user.try(:admin?) %>
<%= link_to "Modifier l'hiragana", edit_hiragana_path(#hiragana), class: "btn btn-default btn-md" %>
<% end %>
<%= link_to "Voir tous les hiraganas", hiraganas_path, class: "btn btn-default btn-md" %>
</div>
</div>
</div>
</div>
</div>
The controller instance variable #hiragana_and_katagana_attributes has not been given a value within the context of the #show action, at least not in a way that's immediately visible. Wherever you are expecting this object to get instantiated, that's not happening.

Resources