i want to display the search item name in search page as heading.
(here it is displaying value instead of name)
I am searching through ransack.
My search view
<%= form_tag location_path, :method=>'get' do %>
<%= select_tag :q, options_from_collection_for_select(Category.all, :id, :name, params[:q]), :class=>"btn1 btn-default1 dropdown-button1 dropdown-toggle"%>
<input type="submit" value="SEARCH" class="btn1 home-search-button" >
<%end %>
my search controller
def location
q = params[:q]
#key = q
#property = Property.ransack(location_or_category_name_cont: q).result(distinct: true)
end
MY location.html.erb
HERE IS WHERE I WANT DISPLAY THE PROPERTY NAME as
<h1>Properties in <%=#key%></h1>
i am getting output like this.
BUT, instead of 2, I want to get output like this Properties in Residential.
I have a category table with 3 category with fields id(1 ,2,3) and category_names (residential commericial and Finance.
Any help is appreciatable
Assuming category_name is the column of your categories table:
#key = Category.find(q).category_name
use this code:
#key = Category.find_by(:id=>q)
In view:
<h1>Properties in <%= #key.category_name if #key.present?%></h1>
Related
I have two models: space and booking. Space has_many bookings and Booking has two date attributes: check_in and check_out.
Given a valid date range, I want to show all spaces available during this range
This is the view:
<%= form_tag spaces_path, method: :get do %>
<%= date_field_tag :query1,
params[:query1],
class: "form-control" %>
<%= date_field_tag :query2,
params[:query2],
class: "form-control" %>
<%= submit_tag "Search", class: "btn" %>
<% end %>
This is the SpaceController:
(...)
def index
if params[:query1].present? && params[:query2].present?
query1 = DateTime.parse(params[:query1])
query2 = DateTime.parse(params[:query2])
search = query1..query2
bookings = Booking.all
# returns the bookings that overlaps with the search
overlapping_bookings = bookings.select do |booking|
check_in = booking[:check_in]
check_out = booking[:check_out]
period = check_in..check_out
search.overlaps?(booking.period)
end
# returns the spaces_id of the bookings that overlaps
overlapping_space_ids = overlapping_bookings.select do |overlapping_booking|
overlapping_booking[:space_id]
end
# remove the duplicates
overlapping_space_ids.uniq!
# remove the spaces with bookings that overlap with the search
#spaces = Space.all.reject do |space|
overlapping_space_ids.include? space[:id]
end
else
#spaces = Space.all
end
end
(...)
I assume the root cause of my problem is that I'm treating the Active Record Query Object as an array of hashes, not sure if it's correct. I made some researches on this but I haven't found any exhaustive answer.
Using an SQL subquery (in PostgreSQL for example) you would do this:
sql = <<SQL
SELECT *
FROM spaces
WHERE id in (
SELECT space_id
FROM bookings
WHERE
(check_in, check_out) OVERLAPS (:from, :to)
)
SQL;
Booking.find_by_sql([sql, {from: query1, to: query2})
Hope that helps :)
I would add a scope to the Booking model first:
# in app/models/booking.rb
scope :overlapping, ->(from, to) {
where(
"(check_in, check_out) OVERLAPS (?, ?)", from, to
)
}
and would then change the whole controller method to:
def index
#spaces = Space.all
if params[:query1].present? && params[:query2].present?
from = DateTime.parse(params[:query1])
to = DateTime.parse(params[:query2])
#space = #space.where.not(
id: Booking.select(:space_id).overlapping(from, to)
)
end
end
I created a rails (v5) form with multiple select and collection_select elements.
Then I use Select2-rails (v4.0.3) to allow a nice selection looking like tags.
The search-options are pulled by ajax.
It works fine until one presses the submit-button with missing required fields.
Valid field-content has now been deleted from the field.
Let me give some example-code:
controller:
...
def form
if params[:form_request].nil?
#form_request = FormRequest.new
else
#form_request = FormRequest.new(params[:form_request])
end
end
def request_form
#form_request = FormRequest.new(params[:form_request])
if #form_request.valid?
render :summary
else
render :form
end
end
...
form:
...
<%= bootstrap_form_for(#form_request, url: '/form/request_form') do |f| %>
<%= f.select :field, [], {label: 'Field label'} %>
<%= f.submit "Submit form" %>
<% end %>
:field is for sure a writable field in the model (and data is set fine)
coffee-script:
Query ->
$("#form_request_from").select2({
ajax: {
url: func =(params) ->
filter = params.term
return "/data.json?filter=" + filter;
,
dataType: 'json',
processResults: processData
},
theme: 'bootstrap',
placeholder: 'Enter data here'
});
processData = (data) ->
mapdata = $.map(data, func =(obj) ->
obj.id = obj.id;
obj.text = obj.name;
return obj;
);
return { results: mapdata };
I am thinking of a lot of possibilities, but at the end I am not sure where the field-data comes from. It is inside the object, but it isn't written to the resulting HTML in any way.
And even if the id would be written as a selected option,
the select2 script would need to know how to transform that into the string to show the real data.
Any idea how to achieve that the data is still written into a field after a failing validation?
After trying out some things I found out how to do it.
At first I just changed the empty array to be the :field variable,too.
This doesn't work too well because it only remembers the ID of the value that has been entered before and like this the SELECT2-script could not find the value to that key and nothing is shown.
Then I created a new variable inside the controller in which I place the array with name and id:
field_object = ObjectsModel.find(#form_request.field.to_i)
#form_field = []
if !field_object.nil?
#form_field = [[field_object.name, field_object.id]]
end
And in the view I now use this field to show the available options:
<%= bootstrap_form_for(#form_request, url: '/form/request_form') do |f| %>
<%= f.select :field, #form_field, {label: 'Field label'} %>
<%= f.submit "Submit form" %>
<% end %>
This works perfectly fine for me without the need to touch the SELECT2-script.
The possible values are still fetched by AJAX but already filled out fields will persist upon redirect to another action.
I have private method on controller
private
def set_address
#address = Address.find(params[:id])
end
def city_options
#city_options = []
if #address
#city_options = City.where(province_id: #address.province_id).collect{ |x| [x.name, x.id] }
end
end
And on views of _form.html.erb
<%= f.select :city_id, #city_options, { :prompt => I18n.t('prompt.select_city') }, class: 'select-city text address-city' %>
It's fine on new form and edit has right selected value, but when I encrypt the id in city_options method
#city_options = City.where(province_id: #address.province_id).collect{ |x| [x.name, encrypted_id(x.id)] }
List of city is shown and value of id is encrypted but wrong selected a value of city, just selected id on top of list.
Wrong value is selected because the saved city_id do not match the encrypted_id of any select list option.
To get over it you can use options_for_select method. Try following if encrypted_id method is a helper method
<%= f.select :city_id, options_for_select(#city_options, selected: encrypted_id(f.object.city_id)), { :prompt => I18n.t('prompt.select_city') }, class: 'select-city text address-city' %>
Check this link http://apidock.com/rails/v3.1.0/ActionView/Helpers/FormOptionsHelper/options_for_select
If encrypted_id method is a controller method, you have pass currently selected value by encrypting it from controller. Or you can use
helper_method :encrypted_id in controller to make encrypted_id method available in view and can use above mentioned method
I have a model that has a boolean field called ignored. What I did right up to this point is not display records which have this field set to true by having a default_scope where(:ignored => false).
Now, in my Ransack search form I would like to have a checkbox named Include ignored so the table would also display the records which are ignored along with the ones which aren't.
I got as far as adding the checkbox to my search form f.check_box(:ignored_eq) but when checking this, the list will display ONLY the ignored records. How do I display records in all states when checking this box?
Controller:
def index
#q = Venue.search(params[:q])
#venues = #q.result.page(params[:page]).per_page(15)
end
Search form (HAML):
= search_form_for #q, url: [:admin, :venues] do |f|
= f.text_field :name_cont
= f.text_field :locality_name_cont
= f.text_field :categories_name_cont
= f.check_box :ignored_eq
= content_tag :button, type: :submit, class: 'btn' do
= content_tag(:i, "", class: "icon-search")
= t("helpers.links.search")
The desired functionality is: when I enter the page I want to have only the ones that have ignore = false listed and have the box unchecked. When I check the box and submit the form I want to have ignored as well as non-ignored ones displayed. Is this possible with Ransack?
What you can do is use the rewhere AR method.
and have something like that for the ignored flag:
def index
#q = Venue.search(params[:q])
#q = #q.rewhere("ignored = 0 OR ignored = 1") if params[:ignored_eq] == 1
#venues = #q.result.page(params[:page]).per_page(15)
end
you can also use the unscoped method to clear the default_scope
def index
if params[:ignored_eq] == 1
#q = Venue.unscoped.search(params[:q])
else
#q = Venue.search(params[:q])
end
#venues = #q.result.page(params[:page]).per_page(15)
end
which is prettier (IMO)
I have the following problem. I have a form which takes input for a "Chart" object. But after processing the form, i wish to display one of the values, and it adds the key of this value.
Class model
class Chart
attr_accessor :title, :series
def initialize(title = nil, series = [])
#title, #series = title, series
end
end
View of form:
<% form_for :chart , :url => { :action => "show" } do |f| %>
<p>
<%= f.label :title %><br />
<%= f.text_field :title %>
</p>...
<% end %>
Chart controller, show method:
def show
#chart = Chart.new(params[:chart])
end
View of show:
<h2><%=h #chart.title %></h2>
Which displays: "title"input_forms_title""
for example: writing in the input form: Economy, prints in the show view: "titleEconomy"
Any ideas?
I have just figured it out. The problem was in the constructor or initialize method. By changing the initialize method to:
def initialize( options = {} )
#title = options[:title]
#series = []
end
It now accepts all params perfectly!