Rails multiple search parameters and defaults - ruby-on-rails

I have a search form to search incidents model with 3 fields: incidenttype, dayofweek and created_at. In my incidents.index method I check to see if the search param is present. Then filter the results based on the created_at range etc. How would I set this up so that if the dayofweek and incidenttype params were empty or blank it would just not use them in the query filter? Essentially if none were selected do not use those params, only the created_at.
Index method of incidents controller:
def index
if params[:search] && params[:search][:created_at].present?
start_date, end_date = params[:search][:created_at].split(' - ')
#incidents = Incident.where(created_at: start_date..end_date).where(dayofweek: params[:search][:dayofweek]).where(incidenttype: params[:search][:incidenttype])
#dayofweek = params[:search][:dayofweek]
#incidenttypes = Incident.order("incidenttype").distinct.pluck(:incidenttype)
else
#incidents = Incident.all
#incidenttypes = Incident.order("incidenttype").distinct.pluck(:incidenttype)
end
end
Form:
<%= form_for(:search, url: incidents_path, method: :get) do |f| %>
<div class="ui-bordered px-4 pt-4 mb-4">
<div class="form-row">
<div class="col-md mb-4">
<label class="form-label">Type</label>
<%= f.select :dayofweek, Incident.dayofweeks.keys, {:include_blank=> 'Any days', :selected => #dayofweek}, class: 'custom-select' %>
</div>
<div class="col-md mb-4">
<label class="form-label">Incident Type</label>
<%= f.select :incidenttype, options_for_select(#incidenttypes, :selected => params[:search][:incidenttype]), {include_blank: true}, class: 'form-control' %>
</div>
<div class="col-md mb-4">
<label class="form-label">Created date</label>
<%= f.text_field :created_at, class: 'form-control', id: 'tickets-list-created', :autocomplete => :off, value: created_at_from_parameters %>
</div>
<div class="col-md col-xl-2 mb-4">
<label class="form-label d-none d-md-block"> </label>
<button type="submit" class="btn btn-secondary btn-block">Show</button>
</div>
</div>
</div>
<% end %>
Any thoughts on how to set this up?

Replace your index method with:
def index
#incidenttypes = Incident.order(:incidenttype).distinct.pluck(:incidenttype)
#incidents = if params[:search] && params[:search][:created_at].present?
#dayofweek = params[:search][:dayofweek]
start_date, end_date = params[:search][:created_at].split(' - ')
filters = { created_at: start_date..end_date }
[:dayofweek, :incidenttype].each do |filter|
next if params[:search][filter].blank?
filters.merge!({ filter => params[:search][filter] } )
end
Incident.where(filters)
else
Incident.all
end
end

Related

undefined method `appointments_path' using nested resource

I have a nested resource appointments in profiles in route.rb.
resources :profiles, only: [:show, :update, :edit] do
resources :appointments
end
In my AppointmentsController.rb I write new method like this
def new
#appointment = Appointment.new
end
I have form for this new method in appointments/new.html.erb
<section class="login-page border-top-blue padding-v-10">
<section class="login-details-div bg-light-grey">
<%= form_for(#appointment, :html => { :class => 'form-horizontal login-form-container login-form-div' }) do |f| %>
<h1>Create New Appointments</h1>
<div class="form-div-send-for-inlinement-icon-with-text-field">
<span class="form-wrapper ">
<i class="fa fa-user login-icon-white login-icon-envelop "></i>
</span>
<div class="label-input-div input-width">
<label for="" class="login-label-div"></label>
<div class="form-wrapper"><%= f.text_area :description, class:'login-icon-white', autofocus: true %></div>
</div>
</div>
<div class="form-div-send-for-inlinement-icon-with-text-field">
<span class="form-wrapper ">
<i class="fa fa-envelope login-icon-white login-icon-envelop "></i>
</span>
<div class="label-input-div input-width">
<label for="" class="login-label-div">topic</label>
<div class="form-wrapper"><%= f.text_field :topic, class:'login-icon-white' %></div>
</div>
</div>
<div class="form-div-send-for-inlinement-icon-with-text-field">
<span class="form-wrapper ">
<i class="fa fa-envelope login-icon-white login-icon-envelop "></i>
</span>
<div class="label-input-div input-width">
<label for="" class="login-label-div">Appointment Date</label>
<div class="form-wrapper"><%= f.date_field :appointment_date, class:'login-icon-white' %></div>
</div>
</div>
<div class="form-div-send-for-inlinement-icon-with-text-field">
<span class="form-wrapper ">
<i class="fa fa-envelope login-icon-white login-icon-envelop "></i>
</span>
<div class="label-input-div input-width">
<label for="" class="login-label-div">class hours</label>
<div class="form-wrapper"><%= f.number_field :class_hours, class:'login-icon-white' %></div>
</div>
</div>
<div class="form-group">
<label for="" class="col-sm-offset-2 col-sm-10 col-xs-offset-2 col-xs-10 col-md-offset-1 col-md-11 login-btn-div">
<%= f.submit "submit", :class => "login-btn" %>
</label>
<label for="" class="col-sm-offset-2 col-sm-10 col-xs-offset-2 col-xs-10 col-md-offset-1 col-md-11 login-btn-div">
<%= link_to "Cancel", root_path(), :class => "login-btn" %>
</label>
</div>
<% end %>
</section>
</section>
I have a link tag in profiles/show.html.erb for callling this new method of AppointmentsController.rb .
<%= link_to "book a class", new_profile_appointment_path, class: 'btn-green2' %>
I don't understand why whenever I click this link I got link in url
http://localhost:3000/profiles/3/appointments/new
which is I need.But there is an error
undefined method 'appointments_path' for #<#<Class:0x007f24ccc16bf8>:0x007f24ccc154b0>
I could not figure out my fault here.Please help.
As you are using nested resources for creating every appointment you need a profile under which your appointment will be nested. So you need to pass profile_id under which your appointment will be created as your path new_profile_appointment_path is also saying.
<%= form_for([#profile, #appointment], :html => { :class => 'form-horizontal login-form-container login-form-div' }) do |f| %>
You also need to define #profile in your method.
def new
#profile = Profile.find(params[:profile_id])
#appointment = Appointment.new
end
Url in your form should be smth like this:
<%= form_for [#profile, #appointment] do |f| %>
...
<% end %>
form_for tries to use existing paths. You don't have an appointments_path but you do have an profile_appointments_path
To use that path, just pass both objects to the form_for
<%= form_for([#profile, #appointment], :html => { :class => 'form-horizontal login-form-container login-form-div' }) do |f| %>
However, this does mean you need to create an instance variable #profile in your new method...
def new
#profile = Profile.find(params[:profile_id])
#appointment = Appointment.new
end

rails nested form for many to many not working as expected

I have 3 models,
the relationship between those models is many to many relationship.
unit model
has_many :unitrentperiods, inverse_of: :unit
has_many :rentperiods, :through => :unitrentperiods
accepts_nested_attributes_for :unitrentperiods
unitrentperiod model
belongs_to :unit
belongs_to :rentperiod
rentperiod model
has_many :unitrentperiods, inverse_of: :rentperiod
has_many :units, :through => :unitrentperiods
and i have a unit form, where i can create a new unit or edit an unit.
i want to make my unit form not just able to manage my unit but able to manage my "unitrentperiod" as well, so lets say i have 2 rent periods like
"6 months"
"12 months"
i want my unit form to display those rent periods also with price input, so when i save my unit form, i also save 2 unitrentperiod based on rent periods in database, i did this in my view:
<style>
.divCB {
margin-right: 10px
}
</style>
<%= form_for(#unit) do |f| %>
<% if #unit.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#unit.errors.count, "error") %> prohibited this unit from being saved:</h2>
<ul>
<% #unit.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<% end %>
<div class="page-header">
<div class="row">
<div class="col-md-7">
<h1 class="h2 page-title">Manage Unit</h1>
<div class="text-muted page-desc"></div>
</div>
<div class="col-md-5 charts">
<div class="row">
</div>
</div>
</div>
</div>
<!-- Breadcrumb -->
<ol class="breadcrumb">
<li class="active">Manage Unit</li>
<!-- Breadcrumb Menu-->
</ol>
<div class="container-fluid">
<div class="animated fadeIn">
<!--/.row-->
<div class="row">
<div class="col-md-6">
<div class="card">
<div class="card-header">
<strong>Unit Form</strong>
</div>
<%= form_for #unit, html: {class: "form-horizontal"} do |f| %>
<div class="card-block">
<div class="form-group row">
<%= f.label 'Apartement', class: 'col-md-4 form-control-label' %>
<div class="col-md-8">
<%= collection_select(:unit, :apt_id, #apts, :id, :apt_name, {:prompt => "Please select an Apartement"}, {:id => 'apartements_select', :class => "select", :style => "width:240px"}) %>
</div>
</div>
<div class="form-group row">
<%= f.label 'Tower', class: 'col-md-4 form-control-label' %>
<div class="col-md-8">
<%= collection_select(:unit, :tower_id, #towers, :id, :tower_name, {:prompt => "Select a Tower"}, {:id => 'towers_select', :class => "select", :style => "width:240px"}) %>
</div>
</div>
<div class="form-group row">
<%= f.label 'Unit number', class: 'col-md-4 form-control-label' %>
<div class="col-md-8">
<%= f.text_field :unitno, class: "form-control" %>
</div>
</div>
<div class="form-group row">
<%= f.label 'Unit size', class: 'col-md-4 form-control-label' %>
<div class="col-md-8">
<%= f.text_field :unitsize, class: "form-control" %>
</div>
</div>
<div class="form-group row">
<%= f.label 'Unit view', class: 'col-md-4 form-control-label' %>
<div class="col-md-8">
<%= f.select :unitview, options_for_select(#unit_views.collect { |s| [s[0].humanize, s[0]] }, selected: #unit.unitview), {} , class: "form-control" %>
</div>
</div>
<div class="form-group row">
<%= f.label 'Room Type', class: 'col-md-4 form-control-label' %>
<div class="col-md-8">
<%= collection_select(:unit, :room_type_id, #roomtypes, :id, :room_type_desc, {:prompt => false}, class: "form-control") %>
</div>
</div>
<div class="form-group row">
<%= f.label 'Unit floor', class: 'col-md-4 form-control-label' %>
<div class="col-md-8">
<%= f.text_field :unitfloor, class: "form-control" %>
</div>
</div>
<div class="form-group row">
<%= f.label 'Unit description', class: 'col-md-4 form-control-label' %>
<div class="col-md-8">
<%= f.text_field :unitdesc, class: "form-control" %>
</div>
</div>
<div class="form-group row">
<%= f.label 'Total bed', class: 'col-md-4 form-control-label' %>
<div class="col-md-8">
<%= f.text_field :totalbedroom, class: "form-control" %>
</div>
</div>
<div class="form-group row">
<%= f.label 'Furnish', class: 'col-md-4 form-control-label' %>
<div class="col-md-8">
<%= f.select :furnish, options_for_select(#furnish_types.collect { |s| [s[0].humanize, s[0]] }, selected: #unit.furnish), {} , class: "form-control" %>
</div>
</div>
<div class="form-group row">
<%= f.label 'For sell', class: 'col-md-4 form-control-label' %>
<div class="col-md-8">
<%= f.select :isforsell, options_for_select( [ ['No', 0], ['Yes', 1] ], selected: #unit.isforsell), {} , class: "form-control" %>
</div>
</div>
<div class="form-group row">
<%= f.label 'Sell price', class: 'col-md-4 form-control-label' %>
<div class="col-md-8">
<%= f.text_field :sellprice, class: "form-control" %>
</div>
</div>
<div class="form-group row">
<%= f.label 'For rent', class: 'col-md-4 form-control-label' %>
<div class="col-md-8">
<%= f.select :isforrent, options_for_select( [ ['No', 0], ['Yes', 1] ], selected: #unit.isforrent), {} , class: "form-control" %>
</div>
</div>
<div class="form-group row">
<%= f.label 'Rent price', class: 'col-md-4 form-control-label' %>
<div class="col-md-8">
<table>
<% #rentperiods.each do |rentperiod| -%>
<tr>
<td><%= rentperiod.rentmonth %> Month</td>
<td>
<%= fields_for(#unitrentperiods) do |elem| %>
<%= elem.text_field :rentprice, class: 'col-md-4 form-control' %> IDR
<%= elem.hidden_field :rentperiod_id, :value => rentperiod.id %>
<% end %>
</td>
</tr>
<% end -%>
</table>
</div>
</div>
<div class="form-group row">
<%= f.label 'Unit status', class: 'col-md-4 form-control-label' %>
<div class="col-md-8">
<%= f.select :unitstatus, options_for_select(#unit_statuses.collect { |s| [s[0].humanize, s[0]] }, selected: #unit.unitstatus), {} , class: "form-control" %>
</div>
</div>
<div class="form-group row">
<%= f.label 'Photo Template', class: 'col-md-4 form-control-label' %>
<div class="col-md-8">
<%= f.select :template_id, options_for_select(#templates.collect { |s| [s[:type], s[:id]] }, selected: #unit.template_id), {} , class: "form-control" %>
</div>
</div>
<div class="form-group row">
<%= f.label 'Floor plan', class: 'col-md-4 form-control-label' %>
<div class="col-md-8">
<div id="divFloorplan">
</div>
</div>
</div>
<div class="form-group row">
<%= f.label 'Unit plan', class: 'col-md-4 form-control-label' %>
<div class="col-md-8">
<div id="divUnitplan">
</div>
</div>
</div>
</div>
<div class="card-footer">
<button type="submit" class="btn btn-sm btn-primary"><i class="fa fa-dot-circle-o"></i> Submit</button>
</div>
<% end %>
</div>
</div>
<!--/col-->
</div>
<!--/.row-->
</div>
</div>
<script>
$(document).ready(function()
{
$('.select').select2();
$('#apartements_select').change(function() {
$.ajax({
url: "/units/gettowers",
data: {
apt_id : $('#apartements_select').val()
},
dataType: "script"
});
$.ajax({
url: "/units/getfloorplans",
data: {
apt_id : $('#apartements_select').val()
},
dataType: "script"
});
$.ajax({
url: "/units/getunitplans",
data: {
apt_id : $('#apartements_select').val()
},
dataType: "script"
});
});
});
</script>
controller
class UnitsController < ApplicationController
before_action :set_unit, only: [:show, :edit, :update, :destroy]
# GET /units
# GET /units.json
def index
#units = Unit.paginate(page: params[:page])
end
# GET /units/1
# GET /units/1.json
def show
end
def gettowers
# updates towers based on apartement selection
tower = Tower.where(:apt_id => params[:apt_id])
# map to name and id for use in our options_for_select
#towers = tower.map{|a| [a.tower_name, a.id]}.insert(0, "Select a Tower")
end
def getfloorplans
floorplans = Floorplan.where(:apt_id => params[:apt_id]).select("id, floorplanphoto")
#imgs = floorplans
end
def getunitplans
unitplans = Unitplan.where(:apt_id => params[:apt_id]).select("id, unitplanphoto")
#imgs = unitplans
end
def preparedata
#master tables
#apts = Apt.all
#towers = Tower.all
#roomtypes = RoomType.all
#rentperiods = Rentperiod.all
array = []
Template.all.each do |t|
hash = { :type => t.room_type.room_type_desc, :id => t.id }
array.push(hash)
end
#templates = array
#enum from model
#unit_views = Unit.unitviews
#furnish_types = Unit.furnishes
#unit_statuses = Unit.unitstatuses
end
# GET /units/new
def new
#unit = Unit.new
#unitrentperiods = #unit.unitrentperiods.build
preparedata
# #rentperiods.each do |r|
# #unit.unitrentperiods.build
# end
end
# GET /units/1/edit
def edit
##unitrentperiods = #unit.unitrentperiods
#unitrentperiods = #unit.unitrentperiods.build
preparedata
end
# POST /units
# POST /units.json
def create
#unit = Unit.new(unit_params)
respond_to do |format|
if #unit.save
format.html { redirect_to #unit, notice: 'Unit was successfully created.' }
format.json { render :show, status: :created, location: #unit }
else
format.html { render :new }
format.json { render json: #unit.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /units/1
# PATCH/PUT /units/1.json
def update
respond_to do |format|
if #unit.update(unit_params)
format.html { redirect_to #unit, notice: 'Unit was successfully updated.' }
format.json { render :show, status: :ok, location: #unit }
else
format.html { render :edit }
format.json { render json: #unit.errors, status: :unprocessable_entity }
end
end
end
# DELETE /units/1
# DELETE /units/1.json
def destroy
#unit.destroy
respond_to do |format|
format.html { redirect_to units_url, notice: 'Unit was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_unit
#unit = Unit.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def unit_params
params.require(:unit).permit(:apt_id, :tower_id, :unitno, :unitsize, :unitview,
:room_type_id, :unitfloor,
:unitdesc, :isforsell, :sellprice, :isforrent, :furnish, :totalbedroom,
:unitstatus, :template_id, :floorplan_id, :unitplan_id,
unitrentperiods_attributes: [:rentprice, :rentperiod_id])
end
end
somehow it's not working. Did i miss something? need some guide to make it work.
At first you don't accept nested attributes, add
accept_nested_attributes_for :unitrentperiods
right below has_many :unitrentperiods
Also, you might need to configure strong parameters to allow that nested attributes parameter (or attr_accessible if you are on Rails 3).
Gotcha here: you have to allow unitrentperiods_attributes, not just unitrentperiods.

Smart_listing Gem sorting

Im integrating Smart_listing gem onto my Rails App. I have a Beer table in my database and a beer_type column. Right now im trying to set up a sorting function where Users can filter different types of beer. Similar to this functionality example.
Right now it will filter each one type of beer perfectly. However whenever there is more than 1 beer type checked, it would not display the beer types together.
product.rb
scope :with_beer_type_ales, -> (product) { where('beer_type ILIKE?', "%ales%") }
scope :with_beer_type_cream, -> (product) { where('beer_type ILIKE?', "%cream%") }
scope :like, ->(args) { where("name ILIKE? OR beer_type ILIKE? OR description ILIKE?", "%#{args}%", "%#{args}%", "%#{args}%")}
products_controller.rb
def index
products_scope = Product.all
# Make users initally sorted by name ascending
products_scope = products_scope.like(params[:filter]) if params[:filter]
products_scope=products_scope.with_beer_type_ales(params[:with_beer_type_ales]) if params[:with_beer_type_ales] == "1"
products_scope = products_scope.with_beer_type_cream(params[:with_beer_type_cream]) if params[:with_beer_type_cream] == "1"
#products = smart_listing_create :products,
products_scope,
partial: "products/list",
page_sizes: [10, 20, 30],
default_sort: {name: "asc"}
end
index.html.erb
<%= smart_listing_controls_for(:products, {class: "form-inline text-left"}) do %>
<div class="form-group filter input-append" id="search">
<%= text_field_tag :filter, '', class: "search form-control",
placeholder: "Search...", autocomplete: :off %>
<button class="btn btn-primary disabled" type="<%= :submit %>">
<span class="glyphicon glyphicon-search"></span>
</button>
</div>
<h4>Sort By Type:</h4>
<ul>
<li class="checkbox">
<label class="checkbox inline">
<%= hidden_field_tag :with_beer_type_ales, "0" %>
<%= check_box_tag :with_beer_type_ales %> Ales
</label>
</li>
<li>
<label class="checkbox inline">
<%= hidden_field_tag :with_beer_type_cream, "0" %>
<%= check_box_tag :with_beer_type_cream %> Cream
</label>
</li>
</ul>
</div>
<% end %>
You want OR not AND. When you specify multiple where clauses in a chain, rails defaults to AND.
q = Beer.where(true)
q = q.or.where('beer_type ILIKE?', "%ales%") if params[:with_beer_type_ales] == "1"
q = q.or.where('beer_type ILIKE?', "%cream%") if params[:with_beer_type_cream] == "1"

Returning the value from a select_tag as a parameter

I have a ruby form with a text box for start_date and one for end date. I need to add a dropdown for status. I added the select_tag and it populates correctly. My problem is how do I get the value that was selected?
Snippet from form:
<div class="modal-body">
<div class="control-group">
<label class="control-label">From</label>
<div class="controls">
<%= text_field_tag "purchase_requests_from_time", Date.today.beginning_of_month, :class => "text date_picker report_start_time_picker" %>
</div>
</div>
<div class="control-group">
<label class="control-label">To</label>
<div class="controls">
<%= text_field_tag "purchase_requests_to_time", Date.today.end_of_month, :class => "text date_picker report_start_time_picker" %>
</div>
</div>
<div class="control-group">
<label class="control-label">Status</label>
<div class="controls">
<%= select_tag :status, options_for_select(get_purchase_request_statuses) %>
</div>
</div>
<div class="control-group">
<label class="control-label">Status2</label>
<div class="controls">
<%= select_tag "status2", options_for_select(get_purchase_request_statuses) %>
</div>
</div>
</div>
Then when I try to access the params in the controller
from_time = params[:purchase_requests_from_time]
to_time = params[:purchase_requests_to_time]
status = params[:status]
status2 = params[:status2]
The time parameters show up fine, the status and status2 parameters are missing.
params = {ActiveSupport::HashWithIndifferentAccess} ActiveSupport::HashWithIndifferentAccess (4 elements)
'purchase_requests_from_time' = "Tue Mar 01, 2016"
'purchase_requests_to_time' = "Thu Mar 31, 2016"
'action' = "export"
'controller' = "purchase_requests"
Any idea what I am doing wrong?
I found my problem. I was missing the form_tag and was using a link_to rather than a submit_tag. This is the code that works
<div class="modal hide" id="download_purchase_requests">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3>Download Purchase Requests</h3>
</div>
<%= form_tag({:action => :export, :controller => :purchase_requests}, :multipart => true) do %>
<div class="modal-body">
<div class="control-group">
<label class="control-label">From</label>
<div class="controls">
<%= text_field_tag "purchase_requests_from_time", Date.today.beginning_of_month, :class => "text date_picker report_start_time_picker" %>
</div>
</div>
<div class="control-group">
<label class="control-label">To</label>
<div class="controls">
<%= text_field_tag "purchase_requests_to_time", Date.today.end_of_month, :class => "text date_picker report_start_time_picker" %>
</div>
</div>
<div class="control-group">
<label class="control-label">Status</label>
<div class="controls">
<%= select_tag :purchase_request_status, options_for_select(get_purchase_request_statuses, :selected => params[:purchase_request_status]) %>
</div>
</div>
</div>
<div class="modal-footer">
Close
<%= submit_tag "Download", :class => "btn", :id => "download-btn", :onsubmit => "$('#download-btn').attr('disabled', 'disabled');" %>
</div>
<% end %>
</div>

Nested form does not validate association model

I'm using rails 3.2 with active record and sqlserver. I have a problem with nested forms. I have a model registration which has many registration details and each has a person associated.
Here is the model
class Registration < ActiveRecord::Base
set_table_name "dbo.EV_INSCRIPCIONES"
set_primary_key "Id"
belongs_to :category, :foreign_key => 'CategoriaId'
has_many :registrationDetails, :foreign_key => 'InscripcionEventoId'
#has_one :group
accepts_nested_attributes_for :registrationDetails
validates_associated :registrationDetails
validates :Refencia, :presence => true
#validates_presence_of :category_id
attr_accessible :registrationDetails, :category, :Eliminada, :FechaInscripcion, :CreationalDate, :Referencia, :PagoRegistrado, :Acreditado, :registrationDetails_attributes
#after_initialize :init
def init
write_attribute :Eliminada, false
write_attribute :Acreditado, false
write_attribute :PagoRegistrado, false
write_attribute :CreationalDate, DateTime.now
write_attribute :FechaInscripcion, DateTime.now
#write_attribute :Referencia, ''
end
def category_id
self.category.id unless category.nil?
end
def category_id=(id)
self.category = Category.find(id)
end
end
class RegistrationDetail < ActiveRecord::Base
set_table_name "dbo.EV_INSCRIPCION_DETALLE"
set_primary_key "Id"
belongs_to :registration, :foreign_key => 'InscripcionEventoId'
belongs_to :category, :foreign_key => 'CategoriaId'
belongs_to :person, :foreign_key => 'ParticipanteId', :primary_key => 'JUGADOR_ID'
attr_accessible :person, :category, :registration, :Eliminada, :person_attributes
accepts_nested_attributes_for :person
validates_associated :person
after_initialize :init
def init
write_attribute :Eliminada, false
end
end
class Person < ActiveRecord::Base
set_table_name "dbo.PKR_JUGADOR"
set_primary_key "JUGADOR_ID"
has_many :registrationDetails
validates_presence_of :CDNI, :CNOMBRES, :CAPELLIDO, :CSEXO,:CCIUDADRESIDENCIA, :DFECHANACIMIENTO
validates :CDNI, :length => { :minimum => 7, :maximum =>8 }
#validate :validate_birth_date
before_save :set_ids
def set_ids
if id.nil?
_id = Person.maximum(:JUGADOR_ID)
self.JUGADOR_ID = _id +1
write_attribute :CNROJUGADOR, _id+1
end
end
after_initialize :init
def init
write_attribute :TIPODOCUMENTO_ID, 1 if read_attribute(:TIPODOCUMENTO_ID).nil?
end
def full_name
self.surname + ", " + self.name
end
protected
def validate_birth_date
errors.add(:birth_date, 'must be a valid datetime') if ((Date.strptime(birth_date, "%d/%m/%Y") rescue ArgumentError) == ArgumentError)
end
end
My view
index.html.erb
<h1><%= t '.title', :name => #event.CNOMBRETORNEO %> </h1>
<%= render 'form_nested' %>
_form_nested
<%= form_for #registration, :url => {:controller => "registration", :action => "save"}, :html => {:class=> 'form-horizontal'} do |f| %>
<legend><%= t '.legend' %></legend>
<% if f.object.errors.any?%>
<div id="error_explanation">
<h3 class="text-error"><%= t '.has-errors' %></h3>
</div>
<% end %>
<input type="hidden" id="event_date" name="event_date" value="<%= #event.DDIAACTIVIDAD.strftime('%Y%m%d') %>" />
<input type="hidden" id="event_id" name="event_id" value="<%= #event.TORNEOPOKER_ID %>" />
<%= f.fields_for :registrationDetails do |d| %>
<%= render 'details_fields' , :f => d %>
<% end %>
<% has_error = f.object.errors.has_key? :category %>
<div class="control-group<%= " error" if has_error %>">
<%= f.label :category, :class=> 'control-label' %>
<div class="controls">
<%= f.hidden_field :category_id %>
<div class="btn-group" data-toggle-name="presenter_category_id" data-toggle="buttons-radio">
<%#categorias.each do |x| %>
<button value="<%= x.Id %>" type="button" class="btn" data-age-from="<%= x.FromAge %>" data-age-to="<%= x.ToAge %>"><%= x.Name %></button>
<%end %>
</div>
<% if has_error %>
<span class="help-inline"><%=f.object.errors[:category].join(", ")%></span>
<% end %>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary"><%= t '.save' %></button>
</div>
<%end%>
_detatails_fields
<%= f.object.errors.inspect %>
<%= f.fields_for :person do |p| %>
<%= render 'person_fields', :f => p %>
<% end %>
_person_fields
<%= f.hidden_field :id %>
<% has_error = f.object.errors.has_key? :CDNI %>
<div class="control-group<%= " error" if has_error %>">
<%= f.label :CDNI, :class=> 'control-label' %>
<div class="controls">
<div class="input-append">
<span class="add-on"><i class="icon-book"></i></span>
<%= f.text_field :CDNI, :class => 'input' %>
<div class="add-on" id="document_loader"><%= image_tag '6-0.gif' %></div>
</div>
<% if has_error %>
<span class="help-inline"><%=f.object.errors[:CDNI].join(", ")%></span>
<% end %>
</div>
</div>
<% has_error = f.object.errors.has_key? :DFECHANACIMIENTO %>
<div class="control-group<%= " error" if has_error %>">
<%= f.label :DFECHANACIMIENTO, :class=> 'control-label' %>
<div class="controls">
<div class="input-append">
<span class="add-on"><i class="icon-calendar"></i></span>
<%= f.text_field :DFECHANACIMIENTO, :class=>'input' %>
<span id="person_age" class="add-on"></span>
</div>
<% if has_error %>
<span class="help-inline"><%=f.object.errors[:DFECHANACIMIENTO].join(", ")%></span>
<% end %>
</div>
</div>
<% has_error = f.object.errors.has_key? :CNOMBRES %>
<div class="control-group<%= " error" if has_error %>">
<%= f.label :CNOMBRES, :class=> 'control-label' %>
<div class="controls">
<div class="input-append">
<span class="add-on"><i class="icon-user"></i></span>
<%= f.text_field :CNOMBRES,:class=>'input' %>
</div>
<% if has_error %>
<span class="help-inline"><%=f.object.errors[:CNOMBRES].join(", ")%></span>
<% end %>
</div>
</div>
<% has_error = f.object.errors.has_key? :CAPELLIDO %>
<div class="control-group<%= " error" if has_error %>">
<%= f.label :CAPELLIDO, :class=> 'control-label' %>
<div class="controls">
<div class="input-append">
<span class="add-on"><i class="icon-user"></i></span>
<%= f.text_field :CAPELLIDO,:class=>'input' %>
</div>
<% if has_error %>
<span class="help-inline"><%=f.object.errors[:CAPELLIDO].join(", ")%></span>
<% end %>
</div>
</div>
<div class="control-group">
<%= f.label :CTELEFONO, :class=> 'control-label' %>
<div class="controls">
<div class="input-append">
<span class="add-on"><i class="icon-certificate"></i></span>
<%= f.text_field :CTELEFONO,:class=>'input' %>
</div>
</div>
</div>
<% has_error = f.object.errors.has_key? :CSEXO %>
<div class="control-group<%= " error" if has_error %>">
<%= f.label :CSEXO, :class=> 'control-label' %>
<div class="controls">
<%= f.hidden_field :CSEXO %>
<div class="btn-group" data-toggle-name="presenter_sex" data-toggle="buttons-radio">
<button type="button" class="btn" value="M"><%= t '.masculine' %></button>
<button type="button" class="btn" value="F"><%= t '.femenine' %></button>
</div>
<% if has_error %>
<span class="help-inline"><%=f.object.errors[:CSEXO].join(", ")%></span>
<% end %>
</div>
</div>
<% has_error = f.object.errors.has_key? :CCIUDADRESIDENCIA %>
<div class="control-group<%= " error" if has_error %>">
<%= f.label :CCIUDADRESIDENCIA, :class=> 'control-label' %>
<div class="controls">
<div class="input-append">
<span class="add-on"><i class="icon-map-marker"></i></span>
<%= f.text_field :CCIUDADRESIDENCIA,:class=>'input' %>
</div>
<% if has_error %>
<span class="help-inline"><%=f.object.errors[:CCIUDADRESIDENCIA].join(", ")%></span>
<% end %>
</div>
</div>
And finally the controller
class RegistrationController < ApplicationController
def index
date = "20120729"
id = 1
#id = params[:event_id] unless params[:event_id].nil?
#date = params[:event_date] unless params[:event_date].nil?
#event = Event.find(date,id)
#groups = Group.all
#categorias = Category.where("DiaActividad = ? and TorneoId = ?", date, id)
#registration = Registration.new
#registration.registrationDetails.build( :person => Person.new)
end
def save
#registration = Registration.new(params[:registration])
if #registration.save
redirect_to :controller => 'home'
else
date = params[:event_date]
id = params[:event_id]
#event = Event.find(date,id)
#groups = Group.all
#categorias = Category.where("DiaActividad = ? and TorneoId = ?", date, id)
render :action => 'index'
end
end
end
What is happening? well first of all, the changes on any field are not saved, and the validations are not displayed. When i submit the form, it returns to the same page, and seems the form has errors but no one is displayed, and the data is lost.
Hope you can help me.
Thanks in advance
Well, I don´t Know why but I solved using resources.
In my routes.rb file
resources :registrations
Before I have something like this.
match 'registration/(:event_date)/(:event_id)' => 'registration#index'
match 'registration/save' => 'registration#save'
I think the problem was my custom routes. But i really don`t know.

Resources