rails - multiple paths for a search form - ruby-on-rails

I'm implementing the website. I got a problem for a search form. I upload my code, and what i want to ask is how to set the search 'path' through 'index' and 'historical' on homes_controller
Below, my code:
app/controllers/homes_controller
def index
#homes = Home.where(:category => 1).reverse
end
def historical
#homes = Home.where(:category => 2).reverse
end
app/views/layouts/application.html.erb
Below, this code is temporary code for now. I should change it.
<%= form_tag(homes_path, :method => 'get', id: "search-form" do %>
<%= text_field_tag :search, params[:search], placeholder: "검색" %>
<%= submit_tag "검색", :name => nil %>
<% end %>

Am not sure what you are supposed to do here
But as per the question - I can give a solution to your problem
Keep an instance variable in your controller actions - like this
app/controllers/homes_controller
def index
#homes = Home.where(:category => 1).reverse
#search_path = "path you want to give"
end
def historical
#homes = Home.where(:category => 2).reverse
#search_path = "path you want to give"
end
and in your layout you can use it like this
app/views/layouts/application.html.erb
<%= #search_path.present? %>
<%= form_tag(#search_path, :method => 'get', id: "search-form" do %>
<%= text_field_tag :search, params[:search], placeholder: "검색" %>
<%= submit_tag "검색", :name => nil %>
<% end %>
<% end %>

Related

Rails 5: Two search form_tags on the same page

I'm trying to implement a two search form_tag on a the same page, each search form is placed inside dynamic bootstrap tabs. The first one which is working is basic a search form with one field. The second one which is not working has two fields, one is the same search method as the first and the other I'm trying to get the address from the other_location field and via params[:other_location].
With the current setup the other_location field form the second form does not appear!
Both of the forms are inside partials and I am rendering them inside two dynamic bootstrap tabs like this:
<%= render 'pages/search' %>
<%= render 'pages/search_other' %>
<%= form_tag search_items_path, :method => "get" do %>
<%= text_field_tag :search, params[:search], autofocus: true,
class: "search-query search_size",
placeholder: "Enter product to search" %>
<%= submit_tag "Search", name: nil, :style => "display: none;" %>
<%end%>
<%= form_for :search_other_path, :method => "get" do |form| %>
<%= form.text_field :search, autofocus: true,
class: "search-query search_size",
placeholder: "Enter keyword to search" %>
<% form.fields_for :other_location_path, :method => "get" do |f| %>
<%= f.text_field :other_location, class: "search-query search_size",
placeholder: "Enter address to search" %>
<%= form.submit "Search", name: nil, :style => "display: none;" %>
<%end%>
<%end%>
model
def self.search(search)
return where("0=1") if search !~ /\w{4}/
where("lower(title) LIKE lower(:term)", term: "%#{search}%")
end
routes.rb
get 'search' => 'pages#search', as: 'search_posts'
get 'search' => 'pages#search_other', as: 'search_other'
get 'search' => 'pages#other_location', as: 'other_location'
controller:
def search_other
if params[:search]
#posts = Post.near(other_location,10).search(params[:search]).page(params[:page])
else
#posts = []
end
end
def other_location
other_location = params[:other_location]
if params[:other_location]
Geocoder.search(params[:other_location])
end
end
def search
if params[:search]
#posts = Post.near(action,10).search(params[:search]).page(params[:page])
else
#posts = []
end
end
On your route file:
get 'search/other' => 'pages#search_other', as: 'search_other'
get 'search' => 'pages#search_other', as: 'search_other_items'
both GET requests are going to your pages_controller.rb #search_other method. So even if you have the two form_tags sending the data to different paths (search_other_path, and search_other_items_path) it would be going to the same controler method - which is redundant.
On your actual HTML you have two form tags:
<%= form_tag search_items_path, :method => "get" do %>
and
<%= form_tag search_other_items_path, :method => "get" do %>
You have not mentioned search_items_path in your routes, so I have no idea where that's pointing to. Likely its a proper controller that works since you mentioned the first form was the only one working.
Now, your mentioned controller only has a search method. So to start you are looking at the wrong controller. You should be looking at the controller methods being referenced by the form's action.
In this case, the second form is sending it's request to search_other_items_path which according to your routes, its pointing to pages_controller.rb -> #search_other method.
You should edit your question to include code that is actually relevant. Maybe then I can actually help.

How to do the calculation without any models in Rails?

I need to get an integer(#integer) from the form in my root_path, do multiplication (#integer*45) and display the result on the same page. How can I do it without any models in my application?
Please, share your best practice. Thank you!
I was trying to do next:
CalculatorsController
def calculation
#integer = params[:integer]
#result = #integer*45
end
def result
end
root.rb
root :to => 'calculators#result'
resources :calculators, :collection=>{:result => :get, :calculation => :post}
calculators/result.html.erb
<% form_tag root_path, :html => {:method => :post} do %>
<%= label_tag 'integer' %>
<%= text_field_tag :integer %>
<div><%= submit_tag 'OK' %></div>
<% end %>
I'll do it with ajax, so there is no need for page refresh:
First, update the routes, for your example you only need two routes, one get (or root) and one post.
routes.rb:
Rails.application.routes.draw do
root 'calculators#result'
post 'calculators/calculation'
end
Next, update your view:
Change the url in your form_tag where the data will be sent (to calculation action instead of result).
Add remote: true option to enable ajax.
Add a tag where you will display your result.
result.html.erb:
<% form_tag calculators_calculation_url, remote: true do %>
<%= label_tag 'integer' %>
<%= text_field_tag :integer %>
<div><%= submit_tag 'OK' %></div>
<% end %>
<div id="total"></div>
And create a view for calculation action, but since you are using ajax, you will create it as js.erb and include the required javascript (or jQuery) to update your view (i'm using jQuery in the example).
calculation.js.erb:
$('#total').html('<%= #result %>')
Now when you click submit, your form will be sent to calculation action and will update the div with #result.
Just add the field to your form...
<% form_tag root_path, :html => {:method => :post} do %>
<%= label_tag 'integer' %>
<%= text_field_tag(:integer, #integer) %>
<% if #result.present? %>
<br>
Result is: <%= #result %>
<br/>
<% end %>
<div><%= submit_tag 'OK' %></div>
<% end %>
And then render result in your calculate...
def calculation
#integer = params[:integer].to_i
#result = #integer*45
render :result
end
Your result view (result.html.erb) is getting its data from the result method, not calculation. Update your controller as follows:
def calculation
#integer = params[:integer]
end
def result
#result = #integer*45
end
You then need a tag to display your result in the view, something like:
<p> <%= #result %> </p>

How to make a link_to that redirects and submits a form

I have a modal that will serve as a disclaimer in my app and I need the link at the bottom of the modal that says "agree & continue" to toggle a boolean and input the time that the boolean was toggled. I have created the button as a form with hidden links but I cant seem to see how to make it submit the form AND redirect to the path i specify. Here is my link_to code now.
<% if current_user.user_record.blank? %>
<%= form_for :user do |f| %>
<% f.hidden_field :disclosure_acceptance, :value => true %>
<% f.hidden_field :disclosure_date, :value => Time.now %>
<%= link_to("Agree & Continue", user_steps_path(current_user), class: "btn btn-primary") %>
<% end %>
<% end %>
First, create a new method in your user_records_controller or at whichever controller action the form is displayed at:
def new
#user_record = current_user.build_user_record
end
Put this in your view:
<% if current_user.user_record.blank? %>
<%= form_for #user_record do |f| %>
<%= f.hidden_field :disclosure_acceptance, :value => true %>
<%= f.hidden_field :disclosure_date, :value => Time.now %>
<%=f.submit "Agree & Continue", class: "btn btn-primary") %>
<% end %>
<% end %>
Make a create action for the user_record that looks like this:
def create
#user_record = current_user.build_user_record(permitted_params)
if #user_record.save
redirect_to user_steps_path(current_user)
else
render :new
end
end
private
def permitted_params
params.require(:user_record).permit(:disclosure_acceptance , :disclosure_date) #etc
end
UPDATE
If you directly want to jump to the 'create' action, you can make your configuration like this:
Add a custom action to your routes:
post 'rate/:article_id' => 'user_records#create' :as => :create_user_record
#or whichever controller/action you wish
You should update the route on your form:
= form_tag create_user_record_path, :method=>'post' do
#etc
In order to create a user_record from the controller, you need to change things a little bit:
def create
current_user.user_record.create(:user_id => current_user.id, :disclosure_acceptance => params[:disclosure_acceptance] , :disclosure_date => params[:disclosure_date])
if current_user.user_record.save
#etc
end

Using observe_field on an field inside a fields_for

I'm trying to observe a field that get generated inside a fields_for loop.
The thing is that the id of that field is generated dynamically.
_form.html.erb
<% form_for #exp, :url => {:action => "update"} do |f| %>
<% f.fields_for:patterns do |builder| %>
<%= render 'pattern_fields', :f => builder %>
<% end %>
<% end %>
_pattern_fields.html.erb
Pattern: <%= f.select(:LC_PATTERN, [['stripes', 'stripes'],
['dots', 'dots'],
['lines', 'lines'],
],{ :prompt => "Please select"}
) %>
<%= observe_field("------", :frequency => 1,
:with => "'id='+value", :function => 'alert(value)')%>
My question is how do i get the id of the field inside the fields_for tag.
I finally got it. Found this solution on the internet...Hope it might be of help to someone else.
In your application_helper.rb, add the following functions:
def sanitized_object_name(object_name)
object_name.gsub(/\]\[|[^-a-zA-Z0-9:.]/,"_").sub(/_$/,"")
end
def sanitized_method_name(method_name)
method_name.sub(/\?$/, "")
end
def form_tag_id(object_name, method_name)
"#{sanitized_object_name(object_name.to_s)}_#{sanitized_method_name(method_name.to_s)}"
end
You can then view the id of the fields generated inside 'fields_for' by using the following code:
<%=form_tag_id(f.object_name, :LC_PATTERN) %>

RubyOnRails sending params with form_remote_tag

I know some will think that i should use form_tag with :remote=>true, but i don't know how to render an entire html output....
My problem is the following:
I have this form that sends a collection through 3 comboxes
<%= form_remote_tag :url => report_client_reports_path, :update => :graphic do%>
<%#= form_tag reporte_client_reports_path%>
<p><%= label_tag :supermercados %>
<%=select_tag "supermercados[]", options_from_collection_for_select(#supermercados, "id", "name"),{:multiple=>true, :id => "supermarkets"}%>
</p>
<p><%= label_tag :cortes %>
<%=select_tag "cortes[]", options_from_collection_for_select(#cortes, "corte_real","cuts"),{:multiple=>true, :id => "cortes"}%>
</p>
<p><%= label_tag :productos %>
<%= select_tag "productos[]", options_from_collection_for_select(#productos, "id", "name"),{:multiple=>true, :id => "products"}%>
</p>
<p><%= submit_tag 'Send' %></p>
<%end%>
If i uncommented this line:
<%#= form_tag reporte_client_reports_path%>
It work good and present me the graph, but not the way i expect to work.
I have detected that using form_remote_tag, it sends all vars with their values, bu i dont know why my controller only see one value of each variable.
here is the controller:
#super = params[:supermarkets]
#superm = []
#super.each do |s|
#superm << Company.find(s).abbr
end
#cuts = params[:cuts]
#prods = params[:products]
#cortesGraph = []
#cortess.to_a.each do |c|
#cortesGraph << "#{RawData.find_by_real_cut(c).cuts}"
end
The objects #superm,#cuts and #products arent receving more than 1 value in the array, is a routing problem or a option i have missed in the form_remote_tag?
And update to simplyfy, what actually is still happening is this:
This Works:
<%= form_tag reporte_client_reports_path do%>
This doesn't:
<%= form_tag reporte_client_reports_path,:remote=>true do%>
The problem is that :remote is not sending my params as array it send all data as 1 var :s
I resolved in functional way, but there might be something very weird with this in my controller:
if request.xhr?
#super = params[:supermercados].to_s.split(",")
#cortess = params[:cortes].to_s.split(",")
#prods = params[:productos].to_s.split(",")
end

Resources