RoR: Trying to search by ID number or License Number - ruby-on-rails

hi so I'm trying to do 2 things, one of them is to basically redirect to a model's ID number so input is "1" and redirects to
localhost:3000/model/1
and the second part is actually doing a search. each model has a text field string for license_no and I want to be able to search and return results
currently, I am not sure how I would combine these into 1 search form if thats possible or if it would require 2 separate search forms
i have a search form with only the license_no field but it always returns no results found...
apologize that the model name isn't in singular, the guide I was using to learn RoR had it that way and everything worked, but I have so many references to renters in my project that it would be a while to find all of them
index.html.erb
<%= form_tag search_renters_path, method: get do |f| %>
<%= text_field_tag :license, nil, placeholder: "License Number" %>
<%= submit_tag 'Search', class: "btn-large" %>
<% end %>
models/renters.rb
class Renters < ActiveRecord::Base
validates_presence_of :license_no
def self.search(params)
renters = Renters.where("license_no LIKE?", "%#{params[:license]}%")
end
end
controller.rb
def search
#renter = Renters.search([params])
end
search.html.erb - snippet
<% if #renter.blank? %>
no results
<% else %>
#show results
<% end %>
editted code
models/renters.rb
def self.search(params)
license_query = "%#{params[:license]}%"
id_query = "%#{params[:id]}%"
renters = Renters.where("license_no LIKE ?", license_query) if params[:license].present?
renters = Renters.where("id LIKE ?", id_query) if params[:id].present?
end
controller
def search
#renter = Renters.search(params)
end
search form
<%= form_tag search_renters_path, method: :get do |f| %>
<%= text_field_tag :license, nil, placeholder: "Driver's License" %>
<%= text_field_tag :id, nil, placeholder: "ID number" %>
<% end %>
I'm trying to use the if present? statements to allow a user to decide whether to input ID No or License No. you don't need to input both just one. currently, if I search for a license no, it returns no results. but when I search for an ID, it returns the relevant result

you can do something like this if you are getting value on params[:licence] from your form submit on your controller action search
controller.rb
def search
#renter = Renters.search(params[:licence])
end
app/models/renters.rb
class Renters < ActiveRecord::Base
def self.search(query)
like_query = "%#{query}%"
renters = Renters.where("id LIKE ? OR license_no LIKE ?", like_query, like_query)
end
end

Related

How can create records using input date and save the param using ROR?

I'm trying to generate records according when somebody choose a date it will save more records according an input value.
Controller
##./app/controller/user_job_controller.rb
def new
#user_job = UserJob.new
end
def user_job_params
params.require(:user_job).permit!
end
Model
#user_job.rb
after_save :save_default_values, :if => :new_record?
private
def save_default_values
if params[:dateadd].to_i > 0
params[:dateadd].to_i.times do |i|
self.name = params[:name]
self.dateuser = params[:dateuser] + i+ 1.day
end
else
self.name = params[:name]
self.dateuser = params[:dateuser]
end
end
View
<%= form_with(model: user_job) do |form| %>
Name:<%= form.text_field :name %>
Date: <%= text_field_tag "dateuser", params[:dateuser].to_i %>
Date added: <%= text_field_tag "dateadd", params[:dateadd].to_i %>
<%= form.submit %>
<% end %>
Example with data:
#form values
Name: test
Date: 23-09-2021
days added: 2
Result Wanted:
#it will do on console or ruby on rails logs
insert into user_jobs (id:1, name:test, dateuser: 23-09-2021),
insert into user_jobs (id:2, name:test, dateuser: 24-09-2021),
insert into user_jobs (id:3, name:test, dateuser: 25-09-2021),
The log is showing that is not
Processing by UserJobsController#create as HTML
Parameters: {"authenticity_token"=>"[FILTERED]", "user_job"=>{"name"=>"test"}, "dateuser"=>"2021-09-24", "dateadd"=>"2", "commit"=>"Create User job"}
Unpermitted parameter: :name
Result log:
insert into user_jobs(created_at: 23-09-2021)
Can you please help me to save the data correctly?
There are some problems in the codes.
1. params are only accessible in controller, you wanted to read it in your model
There are many ways to pass params value to model, for example, you can add attr_accessor :dateadd to the model.
But I think a clearer way is to extract the behavior in :save_default_values into a new public method and call it in the controller.
2. params[:name] is an attribute in the model, you should use strong parameters to assign the attributes
3. it's apparently that dateuser is a column of user_jobs, isn't it?
We can use date_field to pick the date and also add this field into strong parameter.
4. After a record saved, that record is not new record any more since it has id value.
Try to use after_create or after_save on: :create. However, I don't use this callback in the code below, but it's just personal choice :)
# user_job.rb
class UserJob < ApplicationModel
# add new public method
def add_additional_jobs!(days)
(1..days).each do |n|
UserJob.create!(name: name, dateuser: dateuser + n.days)
end
end
end
# user_jobs_controller.rb
class UserJobsController < ApplicationController
def new
#user_job = UserJob.new
end
def create
UserJob.transaction do
#user_job = UserJob.create!(user_job_params)
if params[:dateadd].to_i > 0
#user_job.add_additional_jobs!(params[:dateadd].to_i)
end
end
end
private
def user_job_params
params.require(:user_job).permit(:name, :dateuser)
end
end
Then in the view
<%= form_with(model: user_job) do |form| %>
Name:<%= form.text_field :name %>
Date: <%= form.date_field :dateuser %>
Date added: <%= text_field_tag "dateadd", params[:dateadd].to_i %>
<%= form.submit %>
<% end %>

Rails Search Returning Blank Page

I am trying to implement a simple search feature on my site. Currently, when I use my search bar it will work, but if the result is not found then it will pull up a blank page. I am using PostgreSQL
this is my form in recipes/index.html.erb
<%= form_with(url: recipes_path, method: :get, local: true) do |form| %>
<%= form.text_field(:term, {class: 'form-control', type:'search',
arialabel:'search', placeholder: 'search by recipe name'})%>
<%= form.submit 'Search', class: 'btn btn-dark bg-dark' %>
<% end %>
this is my controller index action in the recipes_controller.rb
def index
#recipes = if params[:term]
Recipe.where('name LIKE ?', "%#{params[:term]}")
else
Recipe.all
end
#categories = Category.all
end
I would like to redirect the user back to to the index view and display a message that says something like "the recipe was not found, please search for a different recipe."
In your Index file,
<%= form_tag('/recepies/', :method => :get, :role => 'form') do %>
<%= text_field_tag :term, :class => "form-control", :placeholder => "Search"%>
<button class='glyphicon glyphicon-search' type="search">
</button>
<% end %>
In your controller,
def index
if params[:term].present?
#recipes = Recepie.all
#recipes = #recipes.find_term(params[:term].strip) if params[:term].present?
if #recipes.blank? {
flash[:notice] = 'the recipe was not found, please search for a different recipe.'
}
end
else
#recipes = Recepie.all
end
end
In your Model,
def self.find_term(term)
recipes = all
recipes = posts.where("recipes.term= ?", term)
end
when I use my search bar it will work, but if the result is not found
then it will pull up a blank page.
So your search works but it has no results.
I would like to redirect the user back to to the index view and
display a message that says something like "the recipe was not found,
please search for a different recipe."
You could do something like #recipes.any? to check if you got some results. If you check in the controller you can redirect and use the flash for messages, or you can simply do it in the view and render the message.
PS: Not that you ask, but I really like to use ransack for complex search functionality.

Fetch Data From Multiple Models In One View

This seems easy but I can't figure out how to do it
I'm trying to implement Ransack search in my rails app and for that I have a generated a model Cofounder which don't have any fields in it and I have association between Cofounder and CustomUser model which has email and other fields but i only want to search through email using ransack, i have this association between these two:
has_many :cofounders
belongs_to :CustomUser
(Do i need to have id if Yes how do i do it)
CoFounder Model
class Cofounder < ActiveRecord::Base
belongs_to :CustomUser
end
CofoundersController
class CofoundersController < ApplicationController
layout "custom_layout", only: [:index]
def index
#q = Cofounder.ransack(params[:q])
#cofounders = #q.result
#cofoundes = CustomUser.all
#countries = Country.all
end
end
and in my index view
<% search_form_for #q, url: cofounders_index_path do |f| %>
<%= f.search_field :email_cont, placeholder: "Search Here" %>
<%= f.submit "Search" %>
<% end %>
<%= select_tag "search_by_country", options_for_select(#countries.collect{|x| [x.name]} , params[:search_by_country] ),{prompt: "Select country"} %><br><br>
<%= select_tag "choose_a_role", options_for_select(#cofoundes.collect{|x| [x.first_name]} , params[:choose_a_role] ),{prompt: "Choose A Role", id: "select", multiple: true} %><br><br>
<% #cofoundes.each do |cofounder| %>
<%= cofounder.email %>
<%end%>
it is giving me error code
undefined method `email_cont' for #
i know email_cont if not a field in cofounder and i'm accessing that field in cofounder which is giving me error, how do i get those values in cofounder for successful Ransack search.
any help would be appreciated :)

Ruby on Rails: Getting Form Input to Model

I'm still learning more about Rails and I'm starting to play around with APIs, but I can't seem to figure out how to get an input from a form to the Model.
I want to take the User input (in the form of a zip code) and have it spit out the weather info at that user location.
Form on home.html.erb
<%= form_tag(root_path) do %>
<%= label_tag :zip, "ENTER YOUR ZIPCODE TO FIND YOUR WEATHER" %><br>
<%= text_field_tag :zip,'', placeholder: "e.g. 91765 " %>
<%= submit_tag "show me the weather!" %>
<% end %>
Controller pages_controller.rb
class PagesController < ApplicationController
def home
#weather_lookup = WeatherLookup.new(params[:zip])
end
end
Model weather_lookup.rb
class WeatherLookup
attr_accessor :temperature, :weather_condition, :city, :state, :zip
def initialize(zip)
self.zip = zip
zip = 91765 if zip.blank?
weather_hash = fetch_weather(zip)
weather_values(weather_hash)
end
def fetch_weather(zip)
p zip
HTTParty.get("http://api.wunderground.com/api/API-KEY-HERE/geolookup/conditions/q/#{zip}.json")
end
def weather_values(weather_hash)
self.temperature = weather_hash.parsed_response['current_observation']['temp_f']
self.weather_condition = weather_hash.parsed_response['current_observation']['weather']
self.city = weather_hash.parsed_response['location']['city']
self.state = weather_hash.parsed_response['location']['state']
end
end
I'm not exactly sure how to get the input from the form to the model. This is literally just to show the weather. I'm not trying to save anything in a database
The form helper defaults to "POST" if you don't provide a method. From the looks of your controller, "GET" is what you want. Here's some documentation to provide additional context. The updated form:
<%= form_tag(root_path, method: "get") do %>
<%= label_tag :zip, "ENTER YOUR ZIPCODE TO FIND YOUR WEATHER" %><br>
<%= text_field_tag :zip,'', placeholder: "e.g. 91765 " %>
<%= submit_tag "show me the weather!" %>
<% end %>
Next, if you try to instantiate your #weather_lookup variable without params[:zip], Rails will throw an error. Adding a conditional to your controller will solve this:
class PagesController < ApplicationController
def home
if params[:zip]
#weather_lookup = WeatherLookup.new(params[:zip])
end
end
end
Be sure your routes are set up. Something defining root should exist in routes.rb. For example:
root "pages#home"
I believe you also have to parse the JSON into a hash inside your model. Adding that to the weather_values method:
def weather_values(weather_json)
weather_hash = JSON.parse weather_json
self.temperature = weather_hash.parsed_response['current_observation']['temp_f']
self.weather_condition = weather_hash.parsed_response['current_observation']['weather']
self.city = weather_hash.parsed_response['location']['city']
self.state = weather_hash.parsed_response['location']['state']
end
Finally, be sure you're referencing #weather_lookup somewhere in your view, else the data won't show. A simple, unformatted example:
<%= #weather_lookup %>
Assuming the logic works in your model, the JSON should render after you submit a ZIP code via the form. I don't have an API key else I would have tested this myself.
It seems like you are not hitting your home controller after you hit submit. Make sure you are routing correctly with
root to: 'pages#home'
and add this to your form
<%= form_tag(root_path, method: 'get') do %>

Sunspot Rails - Can user change what fields to search?

I started using Sunspot to perform searches in my Rails 3 app and I ran into a doubt. Is there a way that I can let the user choose in what fields he/she wants to search. For example, in my app we have:
class Project < ActiveRecord::Base
searchable do
text :name, :content, :keyword
end
end
And in the View the default search bar:
<%= form_tag projects_path, :method => :get do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>
Can I add a radio button or something like that so the user can mark it in order just to search by name, or content or keyword? If yes, how can I make it?
Thanks a lot.
Watch the railscasts on the subject: http://railscasts.com/episodes/278-search-with-sunspot .. in it, Ryan lets user's query optionally by month.
So, if month was sent in:
def index
#search = Article.search do
fulltext params[:search]
with(:publish_month, params[:month]) if params[:month].present?
end
#articles = #search.results
end

Resources