Display all the data in the same page using Rails 3 - ruby-on-rails

I want to display all the data present in the DB in same page where my form is present.I have saved one record.Please help me to show all the data after submit in that same page.
My code are as follows.
views/users/index.html.erb
<%= form_for :users,:url => {:action => 'create'} do |f| %>
<p>
Name: <%= f.text_field :name %>
</p>
<p>
Email: <%= f.email_field :email %>
</p>
<p>
content: <%= f.text_field :content %>
</p>
<p>
<%= f.submit 'Create' %>
</p>
<% end %>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Content</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
controller/users_controller.rb
class UsersController < ApplicationController
def index
#users=User.new
end
def create
#users=User.new(params[:users])
if #users.save
flash[:notice]="User has created"
flash[:color]="valid"
redirect_to :action => 'index'
else
flash[:alert]="User couldnot created"
flash[:color]="invalid"
render 'index'
end
end
end
I want to show in the same index page after submitting the form using Rails 3.Please help me.

This should work
views/users/index.html.erb
<%= form_for :user,:url => {:action => 'create'} do |f| %>
<p>
Name: <%= f.text_field :name %>
</p>
<p>
Email: <%= f.email_field :email %>
</p>
<p>
content: <%= f.text_field :content %>
</p>
<p>
<%= f.submit 'Create' %>
</p>
<% end %>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Content</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% #users.each do |u| %>
<td> <%= u.name%> </td>
<td> <%= u.email%> </td>
<td> <%= u.content%> </td>
<td> <%= link_to 'Show', u %> </td>
<td> <%= link_to 'Edit', edit_user_path(u) %> </td>
<td> <%= link_to 'Destroy', u, :method => :delete, :data => { :confirm => 'Are you sure?' } %> </td>
</tbody>
</table>
controller/users_controller.rb
class UsersController < ApplicationController
def index
#users=User.all
end
def create
#users=User.new(params[:users])
if #users.save
flash[:notice]="User has created"
flash[:color]="valid"
redirect_to :action => 'index'
else
flash[:alert]="User couldnot created"
flash[:color]="invalid"
render 'index'
end
end
end

Related

How can I access to nested fields attributes using nested_forms gem

I am using nested_forms gem in my project, nested_forms uses a partial view to render the line with my nested object attributes, here is my partial view code:
<tr class="fields">
<td>
<%= f.text_field :nombre, class: 'form-control craf' %>
</td>
<td>
<%
concat f.select :idtipodocumento, CrTipoDocumento.all.collect {|p| [ p.nombre, p.id ] }, {prompt: 'Seleccione el tipo de documento'}, :class=>'form-control'
%>
</td>
<td>
<%= f.text_field :documento, class: 'form-control', maxlength: '50' %>
</td>
<% if current_user.email.include? '#cifco.gob.sv' %>
<td>
<%= f.check_box :activo %>
</td>
<td>
<%= f.check_box :impresa %>
</td>
<td>
<%= f.check_box :extra %>
</td>
<% end %>
<td>
<%= f.link_to_remove raw('<i class="fa fa-minus-circle" aria-hidden="true"></i>'), :class =>'btn btn-danger hidden-print' %>
</td>
And here is the code block of the view where this partial is rendering:
<tbody>
<fieldset id="acreditados">
<%= f.fields_for :cr_acreditados, :wrapper => false %>
</fieldset>
</tbody>
So, what I want to do is evaluate if 'impresa' == false and only then render it, but if try f.impresa it says the method 'impresa' doesnt exist for f
Here is the form full code:
<%= nested_form_for(#cr_acreditacion_cliente, :validate => true) do |f| %>
<% if #cr_acreditacion_cliente.acreditaciones == nil %>
<% else %>
<table class="table table-striped table-bordered table-hover" id="AC">
<thead>
<tr>
<th>Evento</th>
<th>Cliente</th>
<th>Stand</th>
<th>Acreditaciones</th>
<th>Acreditaciones Disponibles</th>
<th>Tipo de Acreditacion</th>
</tr>
</thead>
<tbody>
<td><%= #cr_acreditacion_cliente.cr_evento.nombre %></td>
<td><%= #cr_acreditacion_cliente.cr_cliente.nombre %></td>
<td><%= #cr_acreditacion_cliente.cr_stand.codigo %></td>
<td><%= #cr_acreditacion_cliente.acreditaciones %></td>
<td>
<p hidden id="cnt"><%= #cr_acreditacion_cliente.acreditaciones %></p>
<p id="acd">
<%= #counter = #cr_acreditacion_cliente.acreditaciones - #cr_acreditacion_cliente.cr_acreditados.count %>
</p>
</td>
<td><%= #cr_acreditacion_cliente.cr_tipocre.tipo %></td>
</tbody>
</table>
<table class="table table-striped table-bordered table-hover" id="DAC">
<thead>
<tr>
<th>Nombre</th>
<th>Tipo de Documento</th>
<th>Documento</th>
<% if current_user.email.include? '#cifco.gob.sv' %>
<th>Activo</th>
<th>Impresa</th>
<th>Extra</th>
<% end %>
<th class="hidden-print">Acciones</th>
</tr>
</thead>
<tbody>
<fieldset id="acreditados">
<%= f.fields_for :cr_acreditados, :wrapper => false %>
</fieldset>
</tbody>
</table>
<div id="addBtn">
<% if #counter >= 1 %>
<p><%= f.link_to_add raw('<i class="fa fa-plus-circle" aria-hidden="true"></i>'), :cr_acreditados, id: 'btna', :class => 'btn btn-primary lta hidden-print', "data-target" => "#DAC" %></p>
<% else %>
<p class="text-center"><h3>No dispone de mas acreditaciones</h3></p>
<% end %>
</div>
<div class="actions text-center">
<%= f.submit "Guardar Credenciales", :class => 'btn btn-success hidden-print', data: { confirm: 'Favor verifique los datos antes de almacenarlos' }%>
</div>
<% end %>
<% end %>

Issue regarding ajax search rails

I tried to built my search with Ajax and I have added remote: true , and respond_ to block in the controller and I created the partial _xvaziri.html.erb and finally index.js.erb.
But I am not getting the desired results for the Ajax search.
Please refer the images as shown below;
In the above image when I searched for "cash" then I get rendering multiple times in the terminal.
index.html.erb
<% #balance = 0 %>
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="table-responsive myTable">
<table class="table listing text-center">
<tr class="tr-head">
<td>Date</td>
<td>Description</td>
<td>Amount</td>
<td>Discount</td>
<td>Paid</td>
<td>Balance</td>
</tr>
<tr>
<td></td>
</tr>
<a href="#" class="toggle-form" style="float: right;" >Search</a>
<div id="sample">
<%= form_tag xvaziris_path, remote: true, method: :get, class: "form-group", role: "search" do %>
<p>
<center><%= text_field_tag :search, params[:search], placeholder: "Search for.....", autofocus: true, class: "form-control-search" %>
<%= submit_tag "Search", name: nil, class: "btn btn-md btn-primary" %></center>
</p>
<% end %><br>
</div>
<% if #xvaziris.empty? %>
<center><p><em>No results found.</em></p></center>
<% end %>
<%= render #xvaziris %>
</table>
</div>
</div>
</div>
_xvaziri.html.erb
<tr id = "kola" class="tr-<%= cycle('odd', 'even') %>">
<td class="col-1"><%= xvaziri.date.strftime('%d/%m/%Y') %></td>
<td class="col-3"><%= span_with_possibly_red_color xvaziri.description %></td>
<td class="col-1"><%= number_with_precision(xvaziri.amount, :delimiter => ",", :precision => 2) %></td>
<td class="col-1 neg"><%= number_with_precision(xvaziri.discount, :delimiter => ",", :precision => 2) %></td>
<td class="col-1 neg"><%= number_with_precision(xvaziri.paid, :delimiter => ",", :precision => 2) %></td>
<% #balance += xvaziri.amount.to_f - xvaziri.discount.to_f - xvaziri.paid.to_f %>
<% color = #balance >= 0 ? "pos" : "neg" %>
<td class="col-1 <%= color %>"><%= number_with_precision(#balance.abs, :delimiter => ",", :precision => 2) %></td>
</tr>
xvaziris_controller.rb
class XvazirisController < ApplicationController
before_action :set_xvaziri, only: [:show, :edit, :update, :destroy]
def index
#xvaziris = Xvaziri.where (["description LIKE ? OR amount LIKE ? OR paid LIKE ?", "%#{params[:search]}%","%#{params[:search]}%","%#{params[:search]}%"])
respond_to do |format|
format.js
format.html
end
end
def import
Xvaziri.import(params[:file])
redirect_to xvaziris_url, notice: "Xvaziris imported."
end
def show
end
def new
#xvaziri = Xvaziri.new
end
def create
#xvaziri = Xvaziri.new(xvaziri)
if
#xvaziri.save
flash[:notice] = 'Xvaziri Created'
redirect_to #xvaziri
else
render 'new'
end
end
def edit
end
def update
if #xvaziri.update(xvaziri)
flash[:notice] = 'Xvaziri Updated'
redirect_to #xvaziri
else
render 'edit'
end
end
def destroy
#xvaziri.destroy
flash[:notice] = 'Xvaziri was successfully destroyed.'
redirect_to xvaziris_url
end
private
# Use callbacks to share common setup or constraints between actions.
def set_xvaziri
#xvaziri = Xvaziri.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def xvaziri
params.require(:xvaziri).permit(:date, :description, :amount, :discount, :paid)
end
end
index.js.erb
<% #balance = 0 %>
<% #xvaziris.each do |xvaziri| %>
$('#kola').append("<%= j render xvaziri %>");
<% end %>
How should I write the above code in order to find searches in xvaziris#index ?
Secondly, I want to display the no results found when search is nil,blank or empty.I wrote the below code but it is not working.
<% if #xvaziris.empty? %>
<center><p><em>No results found.</em></p></center>
<% end %>
Any suggestions are most welcome.
Thank you in advance.
I revised my index.html and index.js.erb as below;
<% #balance = 0 %>
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="table-responsive myTable">
<table id = "kola" class="table listing text-center">
<thead>
<tr class="tr-head">
<td>Date</td>
<td>Description</td>
<td>Amount</td>
<td>Discount</td>
<td>Paid</td>
<td>Balance</td>
</tr>
</thead>
<a href="#" class="toggle-formed" style="float: right;" ><strong>Search</strong></a>
<div id="sample">
<%= form_tag xvaziris_path, remote: true, method: :get, class: "form-group", role: "search" do %>
<p>
<center><%= text_field_tag :search, params[:search], placeholder: "Search for.....", autofocus: true, class: "form-control-search" %>
<%= submit_tag "Search", name: nil, class: "btn btn-md btn-primary" %></center>
</p>
<% end %><br>
</div>
<tbody>
<%= render #xvaziris %>
</tbody>
</table>
</div>
</div>
</div>
index.js.erb
<% #balance = 0 %>
$('#kola tbody').empty();
<% #xvaziris.each do |xvaziri| %>
$('#kola tbody').append("<%= j render xvaziri %>");
<% end %>

Form_tag do not add check_box_tag value into parameters

I have Pieces model, which is store item's parts. When I need, I'm asking to users, check pieces is ok or nok with generated forms.
I am creating reports model to store the forms which I asked from users.
So, when I generate the forms check_box and and text_field works fine. But when I submit the form, I can't get check_box values as a parameter.
{"utf8"=>"✓",
"_method"=>"patch",
"authenticity_token"=>"5OmdXCDixwxru2yBtB3YmT3YF/ZqOByoAJ3J29TyJikxJdA+RXAvGjwu8MBIPlJCROFx4V7AUcA7IIqIgthD9g==",
"notes"=>{"79"=>"asdasda","84"=>""},
"commit"=>"Submit",
"id"=>"5"}
here is my edit.html.erb
<%- model_class = Report -%>
<div class="page-header">
<h1><%=t '.title', :default => [:'helpers.titles.edit', 'Edit %{model}'], :model => model_class.model_name.human.titleize %></h1>
</div>
<% if #report.errors.any? %>
<div id="error_expl" class="panel panel-danger">
<div class="panel-heading">
<h3 class="panel-title"><%= pluralize(#report.errors.count, "error") %> prohibited this report from being saved:</h3>
</div>
<div class="panel-body">
<ul>
<% #report.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
</div>
<% end %>
<table class="table table-striped">
<thead>
<tr>
<th><%= model_class.human_attribute_name(:status) %></th>
<th><%= model_class.human_attribute_name(:serial_no) %></th>
<th><%= model_class.human_attribute_name(:category) %></th>
<th><%= model_class.human_attribute_name(:name) %></th>
<th><%= model_class.human_attribute_name(:brand) %></th>
<th><%= model_class.human_attribute_name(:model) %></th>
<th><%= model_class.human_attribute_name(:quantity) %></th>
</tr>
</thead>
<tbody>
<%= form_tag(report_path(#report), :method => :patch) do %>
<% #pieces.each do |piece| %>
<tr>
<td><div class="form-group">
<%= check_box_tag(:status, name: "status["+piece.id.to_s+"]", class: 'form-control') %>
</div></td>
<td><%= piece.try(:serial_no) %></td>
<td><%= piece.item.category.name %></td>
<td><%= piece.item.name %></td>
<td><%= piece.item.brand %></td>
<td><%= piece.item.model %></td>
<% if piece.serial_no.start_with?("D") %>
<td><%= piece.item.pieces.count %> <%= piece.item.unit.name %></td>
<% else %>
<td><%= piece.item.pieces.sum(:quantity) %> <%= piece.item.unit.name %></td>
<% end %>
</tr>
<tr>
<td colspan=7 class="hidden" id="hebele">
<%= text_field_tag(:note,"", placeholder: "Note ", name: "notes["+piece.id.to_s+"]",class: "form-control ") %>
</td>
</tr>
<% end %>
</tbody>
</table>
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<%= submit_tag("Submit",:class => 'btn btn-primary') %>
<%= link_to t('.cancel', :default => t("helpers.links.cancel")), reports_path, :class => 'btn btn-default' %>
</div>
</div>
<% end %>
<script type="text/javascript">
$("[id='status']").bootstrapSwitch({
size: 'mini',
onColor: 'success',
offColor: 'danger',
indeterminate: true,
onSwitchChange: function(event, state) {
if (state == false){
$("#hebele").removeClass('hidden');
}else if(state == true){
$("#hebele").addClass('hidden');
}
}
});
</script>
controller:
def edit
#pieces = #report.pieces.joins(:item).group(:item_id)
#report = Report.find(params[:id])
end
You need to define the value of the check_box_tag:
<%= check_box_tag :status, piece.id, class: 'form-control' %>
If you're editing a #report, you'll be best using form_for:
<table>
<tbody>
<%= form_for #report do |f| %>
<% #pieces.each do |piece| %>
<tr>
<td>
<div class="form-group">
<%= f.check_box :status, class: 'form-control', price.id %>
</div>
</td>
<td><%= piece.try(:serial_no) %></td>
<td><%= piece.item.category.name %></td>
<td><%= piece.item.name %></td>
<td><%= piece.item.brand %></td>
<td><%= piece.item.model %></td>
<% if piece.serial_no.start_with?("D") %>
<td><%= piece.item.pieces.count %> <%= piece.item.unit.name %></td>
<% else %>
<td><%= piece.item.pieces.sum(:quantity) %> <%= piece.item.unit.name %></td>
<% end %>
</tr>
<tr>
<td colspan=7 class="hidden" id="hebele">
<%= f.text_field :note, placeholder: "Note", class: "form-control" %>
</td>
</tr>
<% end %>
<tr><td colspan="7"><%= f.submit, class: "btn btn-primary" %></td></tr>
<% end %>
</tbody>
</table>

Update page with ajax on form submit - nested routes

I'm trying to do something similar to adding comments to blog posts via ajax but i'm struggling to get it working. In my project, a user can have many activities and each activity can have many items.
The routing is as follows:
resources :users do
resources :activities do
resources :items
end
end
ActivitiesController.rb
#rest of code
def show
#activity = Activity.find(params[:id])
#new_item = #activity.items.build
#items = #activity.items.all.order('id DESC')
end
ItemsController.rb
#rest of code
def create
#activity = Activity.find(params[:activity_id])
#item = #activity.items.new(item_params)
respond_to do |format|
if #item.save
format.html {redirect_to user_activity_path(#activity.user_id, #activity)}
format.js
else
format.html {redirect_to :back}
end
end
end
activities/show.html.erb
<div class="row">
<div class="large-6 large-offset-3 columns">
<%= simple_form_for [#activity, #new_item], url: user_activity_items_path(#activity.user_id, #activity), remote: true do |f| %>
<%= f.input :name, required: false, :wrapper_html => { class: 'large-8 columns name' } %>
<%= f.input :cost, required: false, :wrapper_html => { class: 'large-4 columns cost' } %>
<%= f.submit "Add Item", class: 'large-4 columns button' %>
<% end %>
</div>
</div>
<div class="row">
<div class="large-6 large-offset-3 columns item-list">
<table>
<thead>
<tr>
<th>Name</th>
<th>Cost</th>
</tr>
</thead>
<tbody>
<% #items.each do |item| %>
<%= render 'item', item: item %>
<% end %>
</tbody>
</table>
</div>
</div>
activities/_item.html.erb
<tr>
<td><%= item.name %></td>
<td><%= item.cost %></td>
</tr>
items/create.js.erb
#currently empty
Your create.js.erb should look like
$("#getItems").last('tr').after('<%= escape_javascript(render partial: "activities/item", :locals => { :item => #item })) %>');
And on show page replace this by mine.
<div class="row">
<div class="large-6 large-offset-3 columns item-list">
<table>
<thead>
<tr>
<th>Name</th>
<th>Cost</th>
</tr>
</thead>
<tbody id="getItems">
<% #items.each do |item| %>
<%= render 'item', item: item %>
<% end %>
</tbody>
</table>
</div>
</div>

getting textfield value and search result after page after click on search button in ruby on rails

In my search page I have a textfield of zip code and when I enter Zip code in the textfield and click on search button the value of text field is loss and also search result is loss, what I do to stable textfield value of zip code and search result after click on search button. below is my view page:
<%= form_for :search, :url => { :method => :get, :action => :search } do |f| %>
<table width="100%">
<tr>
<td align="center" style="vertical-align:top;" width="35%">
<table>
<tr>
<td align="center">
<%= text_field_tag "tf_Zip",nil,:placeholder =>'Zip' %>
</td>
</tr>
</table>
<table>
<% if !#user.nil? %>
<% #user.each do |uzr| %>
<tr>
<td bgcolor="#CCDBE0" width="40%">
<%= image_tag #user_img.photo.url(:small),:alt => " " %>
<br/>
<div><a style="color:blue;" href = 'profile?id=<%= uzr.id %>'><%= uzr.First_Name + " " + uzr.Last_Name %></a></div>
</td>
<td bgcolor="#CCDBE0" width="60%" style="text-align:center;">
<div class='buttonblck1'><a href='searchings?id=<%= uzr.id %>'>Send Request </a></div>
</td>
</tr>
<% end %>
<% end %>
</table>
<% end %>
and below is controller page
if ( !params[:tf_Zip].blank? or params[:tf_Zip] != "" )
#user = User.find(:all,:conditions=>['"user_Zip" = ? and "id" != ? ',params[:tf_Zip], current_user.id])
end
Kindly suggest me, waiting for your reply.'
Thanks
First:
form_for is meant to be used with an instance of ActiveModel or ActiveRecord.
Use form_tag, if you want to create a form, that is not based on an object.
Second:
as you have not object, where the attributes are stored, you have to provide them yourself.
The value is defined in the second parameter of text_field_tag
i.e. in your controller:
#zip_search = params[:tf_Zip].presence
if #zip_search
#user = ...
end
and in your view:
<%= form_tag url_for( :controller => :search, :action => :search), :method => :get) do %>
<%= text_field_tag "tf_Zip", #zip_search, :placholder => 'Zip' %>
<% end %>

Resources