will _paginate in show views - ruby

I have Categories view which list some items based on which categories the belong
now i want to paginate items on that category
So, in category controllerI have
<code>
def show
#category = Category.find(params[:id])
end
</code>
and in views/categories/show.html.erb
<code>
<%= will_paginate %>
<ul>
<% #category.photos.each do |photo| %>
<li><%= link_to image_tag( photo.image_url(:thumb).to_s ), photo %></li>
<% end %>
</ul>
<%= will_paginate %>
</code>
How to paginate those items ??
I cant understand the documentation github will_paginate however i know that if its just I can easily replace Category.all with
Category.paginate(:page => params[:page], :per_page => 20, :order => 'created_at DESC')
please help??

Try:
def show
#category = Category.find(params[:id])
#photos = #category.photos.order('created_at DESC')
.paginate(page: params[:page], per_page: 20)
end
and in your view, change:
<% #category.photos.each do |photo| %>
into:
<% #photos.each do |photo| %>

Related

Basic Search in Ruby Sinatra ActiveRecord

I'm trying to make a basic search function for a simple product inventory app on Sinatra, but don't know how to make the controller and view to properly output all the products which have similar names to a results page.
SearchPage.erb:
<form action="/search", method="post">
<input type="text" name="product[name]">
Controller:
post '/search' do
#Products = Product.find_by(name: params[:product][:name])
#Products = Product.all(:name.like => "%#{params[:name]}%") #found this on another question
erb :"result"
end
Result.erb
<% #Products.each do |product| %>
<%=product.name %>
<%=product.details %>
EDIT: I was able to make search work based on the suggestion with the following code. Thanks!:
Search.erb View
<form action="/search", method="get">
<input type="text" name="search">
Controller
get '/search' do
#products = Product.all
if params[:search]
#products = Product.search(params[:search])
else
#products = Product.all
end
erb :'results'
end
Model
class Product < ActiveRecord::Base
def self.search(search)
where("name like ?", "%#{search}%")
end
Results.erb View
<% if #products.present? %>
<table>
<td>Product Name</td><td>Company</td>
<% #products.each do |product| %>
<tr><td><%=h product.name %> </td>
<td><%=h product.company.name %></td>
<% end %>
<% else %>
<p>There are no Products containing the term(s) <%= params[:search] %>.</p>
<% end %>
</table>
I notice off the bat you're using a POST method. There is an easier way to do create search functionality for your products. Try this:
Posts Controller:
#products = Product.all
if params[:search]
#products = Product.search(params[:search]).order("created_at DESC")
else
#products = Product.all.order('created_at DESC')
end
end
Posts Model (note: If you are using SQLite keep it as LIKE. If you are using Postgres, change LIKE to ILIKE)
def self.search(search)
where('name like :pat or content like :pat', :pat => "%#{search}%")
end
Search Form (Put into your Result.erb and edit as needed but keep as get method. I personally like using form helpers but you can create a normal form if you'd like)
<%= form_tag(products_path, :method => "get", id: "search-form") do %>
<%= text_field_tag :search, params[:search], placeholder: "Search Posts" %>
<%= submit_tag "Search" %>
<% end %>
Render Results
<% if #products.present? %>
<%= render #products %>
<% else %>
<p>There are no posts containing the term(s) <%= params[:search] %>.</p>
<% end %>
Let me know if this works for you. If not, i'll try help some more.

Using carmen gem with rails

What I am trying to do is show the 2 letter abbreviation code of the countries, i.e 'US'.
After the country is selected I need to show its state or province.
but I am having a problem.
My code looks like
<%= f.select :country_code, region_options_for_select(only_us_and_france) %>
and define this in helper:
def only_us_and_france
Carmen::Country.all.select{|c| %w{US FR}.include?(c.code)}
end
I am using Rails 4.1.0.
I have solved this by :
Step1: Generated migration
rails g migration addStateCodeFieldToAccounts state_code:string
Step2: Define a method inside controller
def subregion_options
render partial: 'subregion_select'
end
Step3: Declare in routes
resources :accounts do
collection do
get 'subregion_options'
end
end
Step4: In view
<div class="input-control select state_input" data-role="input-control">
<%= f.select :country, region_options_for_select(only_us_and_france) %>
</div>
<div class="input-control select state_input" data-role="input-control">
<%= render partial: 'subregion_select', locals: {parent_region: f.object.country} %>
</div>
Step5: Make partial subregion_select
<div id="account_state_code_wrapper">
<% parent_region ||= params[:parent_region] %>
<% country = Carmen::Country.coded(parent_region) %>
<% if country.nil? %>
<em>Please select a country above</em>
<% elsif country.subregions? %>
<%= subregion_select(:order, :state_code, parent_region) %>
<% else %>
<%= text_field(:order, :state_code) %>
<% end %>
</div>
Step6: In my js file written this
$('select#account_detail_country').change(function(){
selectWrapper = $('#account_state_code_wrapper')
countryCode = $(this).val()
url = "/account_details/subregion_options?parent_region="+countryCode
console.log(url)
selectWrapper.load(url)
});
yeah and it works :) Hope this will help you.

How to save many items on one form rails?

I need to save many items to Cart on form, user enter quantity one form, and selected items goes to db, but now save only first entered quantity of item. Why?
my form
<%= form_for #cart_item do |f| %>
<% #category.items.each do |item| %>
<%= item.name %>
<%= f.hidden_field :item_id, :value => item.id %>
<%= f.text_field :qty %>
<% end %>
<%= f.submit %>
<% end %>
And controller
cart_items_controller.rb
class CartItemsController < ApplicationController
before_action :set_cart, only: [:create]
def create
#cart_items = CartItem.create(cart_items_params)
#cart_items.cart_id = #cart.id
if #cart_items.save
redirect_to :back
else
render root_path
end
end
private
def cart_items_params
params.require(:cart_item).permit(:id, :qty, :item_id, :cart_id)
end
def set_cart
#cart = Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
#cart = Cart.create
session[:cart_id] = #cart.id
end
end
There are a few problems here. I'll give you a little bump:
<% #category.items.each do |item| %>
<%= item.name %>
<%= f.hidden_field :item_id, :value => item.id %>
<%= f.text_field :qty %>
<% end %>
For each CartItem, this is going to create an input like this
<input name="qty">
This is problematic because only one (the last one in the DOM) will be submitted. You need to research fields_for and incorporate that into your loop in order to get unique names for each Item in the form.
This same issue follows through into your controller
def cart_items_params
params.require(:cart_item).permit(:id, :qty, :item_id, :cart_id)
end
This is going to look for a single :id, :qty, :item_id, and :cart_id, when in reality you're looking to accept multiple :item_id and :qty fields. You need to research Strong Parameters with nested has_many associations.
Finally you have this
#cart_items = CartItem.create(cart_items_params)
which is going to attempt to create a single CartItem when you're really trying to create multiple items and associate them back to the Cart. You need to research accepts_nested_attributes_for as well as more generally "rails form save has_many association". It's a widely covered topic here on SO and elsewhere.
I do this:
def create
#cart_items = params[:cart_items]
#cart_items.each do |c|
#cart_item = CartItem.new(c)
if #cart_item.qty.present?
#cart_item.cart_id = #cart.id
#cart_item.save
end
end
and form
<%= form_tag cart_items_path do %>
<% #cart_items.each do |cart_item| %>
<%= fields_for "cart_items[]", cart_item do |f| %>
<% #category.items.each do |item| %>
<%= item.name %>
<%= f.hidden_field :item_id, value: item.id %>
<%= f.text_field :qty %>
<% end %>
<%= f.submit %>
<% end %>
<% end %>
<% end %>

skipping(going straight to the show page) the index page if there is only 1 item in the database

How can I skip the index page and go straight to the show page if there is exactly only 1 project update in my database for that project(while also making sure no button gets displayed if there is no update(zero) in the database?
I tried this:
<% if #project.updates.any? %>
<%= button_tag type: "button", :class => "radius" do %>
<% if #project.updates=1 %>
<%= link_to 'Project Update', project_update_path(#project), :style => "color: white" %>
<% else %>
<%= link_to 'Project Updates', all_project_updates_path(#project), :style => "color: white" %>
<% end %>
<% end %>
<% end %>
but i get this error:
undefined method `each' for 1:Fixnum
On this line:
<% if #project.updates=1 %>
What is the proper syntax for this?
Below is the relevant code:
My button:
<% if #project.updates.any? %>
<%= button_tag type: "button", :class => "radius" do %>
<%= link_to 'Project Updates', all_project_updates_path(#project), :style => "color: white" %>
<% end %>
<% end %>
These is my custom route:
get 'all_project_updates/:id' => 'project_updates#index', as: 'all_project_updates'
These are the final generated routes:
project_updates_path GET /project_updates(.:format) project_updates#index
project_update_path GET /project_updates/:id(.:format) project_updates#show
This is my projects controller(show action)
def show
#project = Project.find(params[:id])
#comments = Comment.all.where(:project_id => #project.id)
#updates = ProjectUpdate.all.where(:project_id => #project.id)
end
And this is my project updates controller index action:
def index
#projectUpdates = ProjectUpdate.where(:project_id => params[:id])
respond_to do |format|
format.html
end
end
And this is my project updates controller show action:
def show
#projectUpdate = ProjectUpdate.find(params[:id])
respond_to do |format|
format.html
end
end
You probably meant:
<% if #project.updates.count == 1 %>
== is for comparison, = is usually for assignment. Also, you need to compare updatesnumber to1(you can get number withcountmethod), notupdates` themselves.
Instead of comparison, you can use Enumerable#one? method:
<% if #project.updates.one? %>

How can I have custom result with autocomplete

In view:
<%= text_field_with_auto_complete :vendor, :number, {}, {:with => "'vendor[number]=' + $('vendor_number').value"} %>
In Controller:
auto_complete_for :vendor, :number do |vendors, params|
vendors.vendor_company_filter(params[:company_id])
end
It works fine, gives list of vendor number as a result
but I need "vendor name + vendor number" in a result list, how can I achieve this..??
please help..
found an easy way,
in Controller
def auto_complete_for_vendor_number
#vendors = Vendor.find_by_number(number)
render :partial => 'auto_complete_for_vendor_number'
end
in _auto_complete_for_vendor_number.html.eb partial:
<ul>
<% #vendors. each do |vendor| %>
<li><%= vendor.name+'('+vendor.number+')' %></li>
<% end %>
</ul>
It worked fine :)

Resources