I have a model called Listing that I use to represent a listing for a sublet. I created a model called Filter that I use to filter the sublets based on a form that the user fills out. Upon filling out the form, I want the user to be redirected to a template that has all of the listings that were returned from the filter.
Here is my Filter model.
class Filter < ActiveRecord::Base
attr_accessible :air_conditioning, :available_rooms, :bathrooms, :furnished, :negotiable, :new, :parking, :maximum_price, :private_bathroom, :show, :term, :total_rooms, :utilities, :washer_dryer
serialize :term
def listings
#listings ||=find_listings
end
private
def find_listings
listings=Listing.order(:price)
listings=Listing.where("listings.price <= ?", maximum_price) if maximum_price.present?
listings=Listing.where(total_rooms: total_rooms) if total_rooms.present?
listings=Listing.where(available_rooms: available_rooms) if available_rooms.present?
listings=Listing.where(bathrooms: bathrooms) if bathrooms.present?
listings=Listing.where(term: term)
listings=Listing.where(furnished: furnished)
listings=Listing.where(negotiable: negotiable)
listings=Listing.where(utilities: utilities)
listings=Listing.where(air_conditioning: air_conditioning)
listings=Listing.where(parking: parking)
listings=Listing.where(washer_dryer: washer_dryer)
listings=Listing.where(private_bathroom: private_bathroom)
listings
end
end
Here is the show method for filter.
<p id="notice"><%= notice %></p>
<%= render (#filter.listings) %>
Pretty simple.
And here is the template called _listing.html.erb
<div style="padding:5px">
<%= link_to 'New Listing', new_listing_path,{:style=>'', :class => "btn"} %>
<h1>Available Sublets</h1>
<table id="listingTable" class="table table-bordered table-hover">
<tr>
<th><%= link_to 'Filter', new_filter_path,{:style=>'', :class => "btn"} %><%= link_to 'Clear Filter', listings_path, {:style=>'', :class => "btn"} %></th>
<th>Address</th>
<th><u><%= "Price Per Month" %></u></th>
<th>Description</th>
</tr>
<% if #listings !=nil %>
<% #listings.each do |listing| %>
<tr onmouseover="this.style.cursor='pointer';"
onclick="window.location.href = '<%= url_for(:controller => 'listings', :action => 'show', :id=>listing.id) %>' " >
<td><%= image_tag listing.photo.url(:small) %></td>
<td><%= listing.address %></td>
<td>$<%= listing.price %></td>
<td width="40%"><%= listing.description %></td>
</tr>
<% end %>
<% end %>
<% else if #listings==nil %>
<p> Sorry, No Sublets Fit Your Criteria! </p>
<% end %>
</table>
However, the filter never returns any results... I have tested atleast 20 times with queries that should definitely return atleast 1 listing. I feel like I have a naming convention problem but I have never used partials before. any help would be great.
This code:
listings=Listing.where(term: term)
listings=Listing.where(furnished: furnished)
listings=Listing.where(negotiable: negotiable)
listings=Listing.where(utilities: utilities)
listings=Listing.where(air_conditioning: air_conditioning)
listings=Listing.where(parking: parking)
listings=Listing.where(washer_dryer: washer_dryer)
listings=Listing.where(private_bathroom: private_bathroom)
Is not actually filtering listings down further. Basically, it's reassigning listings again and again and again.
If you want to apply successive filters to listings, do this:
listings = Listing.where(term: term)
listings = listings.where(furnished: furnished)
listings = listings.where(negotiable: negotiable)
...
Related
I have manager remark model that takes input as a remark and decision value and saves it with the project site ID. I have a project site model that takes input as name, date, and file and stores it. Many remarks have a many to one relation with project site ID, and the project site belongs to the manager remark. I want to access the decision attribute boolean value in project site index form, but I am unable to access that boolean value in the index page of the project site. Here is my code of project site and manager remarks model, view and controller-
project site index.html.erb
<table>
<thead>
<tr>
<th>Name</th>
<th>Date</th>
<th>Attendance</th>
<th>Status</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% #project_sites.each do |project_site| %>
<tr>
<td><%= project_site.name.titleize %></td>
<td><%= project_site.date %></td>
<td><%= link_to ' View attendance', project_site.file, :class => "fi-page-export-csv" %></td>
<td><%= "here i want to access manager remark decision value" %></td>
<td><%= link_to 'Remark ', project_site %><span>(<%= project_site.manager_remarks.size %>)</span></td>
<td><%= link_to 'Edit', edit_project_site_path(project_site) %></td>
<td><%= link_to 'Destroy', project_site, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
</tbody>
project site controller
def index
#project_sites = ProjectSite.all.order("created_at DESC")
#manager_remark = ManagerRemark.joins(:project_site).where(:project_sites => { :user_id => #user.id })
end
# GET /project_sites/1
# GET /project_sites/1.json
def show
#manager_remark = ManagerRemark.new
#manager_remark.project_site_id = #project_site.id
end
# GET /project_sites/new
def new
#project_site = ProjectSite.new
end
def project_site_params
params.require(:project_site).permit(:name, :date, :file)
end
manager_remark controller
class ManagerRemarksController < ApplicationController
def create
#manager_remark = ManagerRemark.new(remark_params)
#manager_remark.project_site_id = params[:project_site_id]
#manager_remark.save
redirect_to project_site_path(#manager_remark.project_site)
end
def remark_params
params.require(:manager_remark).permit(:remark, :decision)
end
end
manager_remark view form
<%= form_for [ #project_site, #manager_remark ] do |f| %>
<div class="row">
<div class="medium-6 columns">
<%= f.radio_button :decision, true %>
<%= f.label :approve %>
<%= f.radio_button :decision, false %>
<%= f.label :reject %>
</div>
<br>
<br>
<div class="medium-6 cloumns">
<%= f.label :remark %><br/>
<%= f.text_area :remark %>
</div>
</div>
<div>
<%= f.submit 'Submit', :class => 'button primary' %>
</div>
<% end %>
routes.rb
Rails.application.routes.draw do
root to: 'home#index'
devise_for :users
resources :project_sites do
resources :manager_remarks
end
get '/project_manager_level_two' => 'project_manager_level_two#index'
get '/project_managers' => 'project_managers#index'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
If I understand correctly, you have a ProjectSite that contains a ManagerRemark with a decision, right? If that's the case, the simple answer is:
<%= project_site.ManagerRemark.decision %>
If you are saying that each ProjectSite has many ManagerRemarks, you'll want to place the above inside a loop, like so:
<% project_site.manager_remarks.each do |manager_remark| %>
<%= manager_remark.decision %><br/>
<% end %>
This assumes that your models are correctly configured to recognize these relationships. The above may also be optimized by adding an include clause to your fetch inside the controller and there's no need to fetch the ManagerRemark objects separately. Therefore, you'd probably want something like:
def index
#project_sites = ProjectSite.all.includes( :manager_remark ).order("created_at DESC")
end
I have a rails application which is not routing as I expected. The search method in the controller is rending show. I've cut down the code to the minimal components and I am posting them here as suggested.
Rails.application.routes.draw do
resources :backups
get 'backups/search' => 'backups#search'
resources :components
resources :backup_media
end
class Component < ActiveRecord::Base
has_many :backups
has_many :backup_media, :through => :backups
end
class BackupMedium < ActiveRecord::Base
has_many :backups
has_many :components, :through => :backups
end
class Backup < ActiveRecord::Base
belongs_to :component
belongs_to :backup_medium
# value to match either the name of the component or backup_medium
def self.search(value)
tables = "backups, components, backup_media"
joins = "backups.backup_medium_id = backup_media.id and components.id = backups.component_id"
c = find_by_sql "select * from #{tables} where components.name like '%#{value}%' and #{joins}"
b = find_by_sql "select * from #{tables} where backup_media.name like '%#{value}%' and #{joins}"
c.count > 0 ? c : b
end
end
class BackupsController < ApplicationController
def search
#backups = Backup.search(params[:search])
render 'index'
end
def index
#backups = Backup.all
end
def show
# this would normally be the code to show an individual backup
# but I'm re-using the code from index because the routing is broken
#backups = Backup.all
end
end
views/backups/_search.html.erb
<%= form_tag backups_search_path, :method => 'get' do %>
<%= label_tag(:search, "Search for:") %>
<%= text_field_tag :search, params[:search], {:placeholder => 'Component or Media' }%>
<%= submit_tag "Search", :name => nil %>
<% end %>
views/backups/index.html.erb
<h1>Listing Backups</h1>
<p id="notice"><%= notice %></p>
<%= render :partial => 'search' %>
<table>
<tr>
<th>id</th>
<th>component_id</th>
<th>backup_medium_id</th>
</tr>
<% #backups.each do |backup| %>
<tr>
<td><%= backup.id %></td>
<td><%= backup.component.name %></td>
<td><%= backup.backup_medium.name %></td>
</tr>
<% end %>
</table>
views/backups/show.html.erb is copied from index.html.erb since it is incorrectly receiving the search results
<h1>Show Backup</h1>
<p id="notice"><%= notice %></p>
<%= render :partial => 'search' %>
<table>
<tr>
<th>id</th>
<th>component_id</th>
<th>backup_medium_id</th>
</tr>
<% #backups.each do |backup| %>
<tr>
<td><%= backup.id %></td>
<td><%= backup.component.name %></td>
<td><%= backup.backup_medium.name %></td>
</tr>
<% end %>
</table>
Suggestions on improving the search method will be welcomed.
As mentioned above, after the search is executed, the show.html.erb is rendered instead of search.html.erb
For a working demo (with better code thanks to suggestions here) see
https://github.com/pamh09/rails-search-demo
You do not have a backups_search_path in your routes, therefore it is treating search in the query string as an id and thus rendering show.html.erb, so try
get 'backups/search' => 'backups#search', as: :backups_search
In debugging I found that rails consistently routed to the wrong view when it was unhappy with the return object coming from the model.
I am working on my first web and Rails app and can not figure out how to get a search feature work from my main page to one of the controllers.
How to send the request and redirect to a results page to show the results from the search.
I can't get this to work as am not sure how to route in a way my variable #histories will keep results and display on the show page.
I would appreciate some insight into search from any page and displaying results on a dedicated page.
Here is what i have so far in terms of the controller, model and partials.
Shipments Model:
def self.search(search)
search_condition = search
find_by_sql("SELECT cargo_transit_histories.current_location,cargo_transit_histories.updated_at FROM cargo_transit_histories
INNER JOIN shipments ON shipments.id = cargo_transit_histories.shipment_id WHERE shipments.tracking_number='search_condition'")
end
Tracking Controller:
def search
#histories = Shipment.search(params[:search])
render('show')
end
Show (Found in Tracking view):
<div class="search_result">
<%= render 'track/search_results' %>
</div>
_search (partial):
<%= form_tag :controller => 'tracking', :action => 'search', :method => 'get' do %>
<%= text_field_tag :search, params[:search], :id => 'search_field' %>
<%= submit_tag "Search", :name => nil %>
<%= link_to_function "Clear", "$('search_field').clear()" %>
<% end %>
_search_results (partial):
<div class="Results list">
<table class="Resultslisting" summary="Result list">
<tr class="header">
<th>Current Location</th>
<th>Date/Time</th>
</tr>
<% if !#histories.empty? %>
<% #histories.each do |result| %>
<tr>
<td><%= result.current_location %></td>
<td><%= result.updated_at %></td>
</tr>
<% end %>
</table>
<% else %>
<p> The tracking number does not exist!</p>
<% end %>
</div>
Try something like the following adapted example:
https://gist.github.com/4173716
But you need to dig a bit deeper into Rails 3 to understand why.
Code in my product model (product.rb):
def self.search(search)
if search
find(:all)
else
find(:all)
end
end
Code in my search controller (search_controller.rb):
def index
#products = Product.search("Apple")
end
Code in my view (index.html.erb):
<h1>Products</h1>
<% form_tag client_search_path , :method => :get do %>
<p>
<%= search_field_tag :term, params[:term], :class=> "auto_search_complete"%>
<%= submit_tag "Search", :name => nil, :class => 'button', :id => "search_bn" %>
</p>
<% end %>
<table border="1px">
<tr>
<th>Name</th>
<th>Brand</th>
<th>Quantity available</th>
<th>Category</th>
<th>Shopcenter name</th>
<th>Shopcenter streetnumb</th>
<th>Shopcenter streetname</th>
<th>Shopcenter postal</th>
<th>Shopcenter province</th>
</tr>
<% for product in #products%>
<tr>
<td><%= product.name %></td>
<td><%= product.brand %></td>
<td><%= product.quantity_available %></td>
<td><%= product.category %></td>
<td><%= product.shopCenter_name %></td>
<td><%= product.shopCenter_streetNumb %></td>
<td><%= product.shopCenter_streetName %></td>
<td><%= product.shopCenter_postal %></td>
<td><%= product.shopCenter_province %></td>
</tr>
<% end %>
</table>
I load this all is good, but if I comment one of the line of codes in my model:
def self.search(search)
if search
#find(:all)
else
find(:all)
end
end
I expect this to work also at least for the initial render, or when I submit an empty search term, but it's not. And changing the code to of the model to:
def self.search(search)
if search
find_all_by_name(search)
else
find(:all)
end
end
Doesn't work it gives me an error that the view is working with a nil object, which is impossible because my database has entries.
Can someone explain what is going on? I have the impression that both the conditions in my model are being executed. At least that's what 2 puts statement in each case showed me.
Please advice.
I think you should set search = nil if search == "" in your controller otherwise it will always go to the first condition.
It had some compatibility issues with Rails 3.
I updated rails and ruby and it works fine now
Learning rails and something smells a little funny.
I have the following form for updating quantities in a shopping cart.
<% form_for(:cart, #cart.items, :url => { :action => "update_cart" }) do |f| %>
<table>
<tr>
<th>Item</th>
<th>Quantity</th>
<th>Price</th>
</tr>
<% for item in #cart.items %>
<% f.fields_for item, :index => item.id do |item_form| %>
<tr>
<td><%=h item.title %></td>
<td><%=item_form.text_field :quantity, :size => 2 %>
<span># <%=h number_to_currency(item.item_price) %></span></td>
<td><%=h number_to_currency(item.line_price) %></td>
</tr>
<% end %>
<% end %>
<tr>
<td colspan="2">Total:</td>
<td><%=h number_to_currency(#cart.total_price) %></td>
</tr>
</table>
<%=submit_tag 'Update Cart' %>
<% end %>
In my update_cart action, I iterate through the existing cart items and set the new quantity:
def update_cart
#cart = find_cart
#cart.items.each do |item|
quantity = params[:cart][:cart_item][item.id.to_s][:quantity].to_i
#cart.update_quantity_for(item, quantity)
end
redirect_to :action => 'cart'
end
I dont have a REST interface controller for carts or cart items. Is there a better way to deal with this deep params data structure? The expression params[:cart][:cart_item][item.id.to_s][:quantity].to_i strikes me as dangerous for invalid form data.
The correct way to do this is the use the "accepts_nested_attributes" attribute in the cart model. Then you can just use CartController's update method to save your items. (http://railscasts.com/episodes/196-nested-model-form-part-1)
Also, your total price should probably be a method defined in the Cart model.