Ruby on rails - Kaminari - Paginate array of search results - ruby-on-rails

I have a search form with pagination. Both things work OK separately, but if I search and then load the next page, the search parameters are forgotten and kaminari shows results regardless of what search options I selected.
I have read through the docs, and other stackoverflow posts but I'm not having any luck.
My index page has
<%= search_form_for #q, html: { id: "gig_search_form" }, remote: true do |f| %>
bla bla bla...
<% end %>
<%= link_to_next_page #gigs, 'Next Page', :remote => true %>
index.js.erb
<% if params[:page] %>
$('.gig-search-list').append("<%= j render(partial: 'gigs') %>");
<% else %>
$('.gig-search-list').html("<%= j render(partial: 'gigs') %>");
<% end %>
gigs partial:
<% #gigs.each do |gig| %>
bla bla bla...
<% end %>
Now, I have tried a few tings in my controller but I'm always gettings the same results. Originally I had;
def index
if params[:search].present?
#q = Gig.notexpired.where(:filled => false).near(params[:search], 500, :order => 'distance' ).ransack(params[:q])
else
#q = Gig.notexpired.where(:filled => false).ransack(params[:q])
end
#allgigs = #q.result(distinct: true)
#gigs = #q.result(distinct: true).page(params[:page]).per(5)
respond_to do |format|
format.js
format.html
end
end
Then;
def index
if params[:search].present?
#q = Gig.notexpired.where(:filled => false).near(params[:search], 500, :order => 'distance' ).ransack(params[:q])
else
#q = Gig.notexpired.where(:filled => false).ransack(params[:q])
end
#allgigs = #q.result(distinct: true)
#gigs = Kaminari.paginate_array(#allgigs).page(params[:page]).per(5)
respond_to do |format|
format.js
format.html
end
end
Then I tried to separate them;
def index
if params[:search].present?
#q = Gig.notexpired.where(:filled => false).near(params[:search], 500, :order => 'distance' ).ransack(params[:q])
else
#q = Gig.notexpired.where(:filled => false).ransack(params[:q])
end
#allgigs = #q.result(distinct: true)
if #allgigs.present?
unless #allgigs.kind_of?(Array)
#gigs = #allgigs.page(params[:page]).per(5)
else
#gigs = Kaminari.paginate_array(#allgigs).page(params[:page]).per(5)
end
end
respond_to do |format|
format.js
format.html
end
end
But I get the same result each time. I can see on the console that when I load more pages, the search parameters are not included.
How can I link the two things together and paginate the search results correctly?
UPDATE:
Server log after loading 'next page' using #chaitanya's answer. I have previously added search params.
Started GET "/gigs?locale=en&page=2" for 127.0.0.1 at 2016-06-29 14:45:53 +0200
Processing by GigsController#index as JS
Parameters: {"locale"=>"en", "page"=>"2"}
Gig Load (10.3ms) SELECT DISTINCT "gigs".* FROM "gigs" WHERE (gigzonetime > '2016-06-29 12:45:53.493341') AND "gigs"."filled" = $1 [["filled", "f"]]
Gig Load (1.2ms) SELECT DISTINCT "gigs".* FROM "gigs" WHERE (gigzonetime > '2016-06-29 12:45:53.493341') AND "gigs"."filled" = $1 LIMIT 5 OFFSET 5 [["filled", "f"]]
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 7]]
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 2]]
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 6]]
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 1]]
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 8]]
Rendered gigs/_gigs.html.erb (13.4ms)
(0.5ms) SELECT DISTINCT COUNT(DISTINCT "gigs"."id") FROM "gigs" WHERE (gigzonetime > '2016-06-29 12:45:53.493341') AND "gigs"."filled" = $1 [["filled", "f"]]
Rendered gigs/index.js.erb (17.2ms)
Completed 200 OK in 54ms (Views: 21.4ms | ActiveRecord: 13.0ms)
Server log when filtering with search form:
Started GET "/gigs?locale=en&utf8=%E2%9C%93&search=&q%5Bdate_gteq%5D=&q%5Bdate_lteq%5D=&q%5Bgenres_id_in%5D%5B%5D=&q%5Bsalary_cents_gteq_euros%5D=0.00&q%5Bsalary_cents_lteq_euros%5D=210.00" for 127.0.0.1 at 2016-06-29 14:45:47 +0200
Processing by GigsController#index as JS
Parameters: {"locale"=>"en", "utf8"=>"✓", "search"=>"", "q"=>{"date_gteq"=>"", "date_lteq"=>"", "genres_id_in"=>[""], "salary_cents_gteq_euros"=>"0.00", "salary_cents_lteq_euros"=>"210.00"}}
Gig Load (0.6ms) SELECT DISTINCT "gigs".* FROM "gigs" WHERE (gigzonetime > '2016-06-29 12:45:47.973892') AND "gigs"."filled" = $1 AND ("gigs"."salary_cents" >= 0 AND "gigs"."salary_cents" <= 21000) [["filled", "f"]]
Gig Load (0.5ms) SELECT DISTINCT "gigs".* FROM "gigs" WHERE (gigzonetime > '2016-06-29 12:45:47.973892') AND "gigs"."filled" = $1 AND ("gigs"."salary_cents" >= 0 AND "gigs"."salary_cents" <= 21000) LIMIT 5 OFFSET 0 [["filled", "f"]]
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 1]]
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 8]]
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 1]]
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 7]]
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 3]]
Rendered gigs/_gigs.html.erb (12.2ms)
(0.4ms) SELECT DISTINCT COUNT(DISTINCT "gigs"."id") FROM "gigs" WHERE (gigzonetime > '2016-06-29 12:45:47.973892') AND "gigs"."filled" = $1 AND ("gigs"."salary_cents" >= 0 AND "gigs"."salary_cents" <= 21000) [["filled", "f"]]
Rendered gigs/index.js.erb (15.6ms)
Completed 200 OK in 33ms (Views: 19.9ms | ActiveRecord: 5.7ms)

try following code to carry your params to next page
= link_to_next_page #gigs, "Next Page", :remote => true, :params => params

You should add the #page and #per methods to the query itself. Kaminari.paginate_array actually takes a slice from the whole array which is not very efficient.
Here's a snippet
def index
if params[:search].present?
#q = Gig.notexpired.where(:filled => false).page(params[:page]).per(5).near(params[:search], 500, :order => 'distance' ).ransack(params[:q]).results
else
#q = Gig.notexpired.where(:filled => false).page(params[:page]).per(5).ransack(params[:q]).results
end
#...
Then use the Kaminari paginate helper in your view
<%= paginate #q %>

Related

Ajax in Rails 5 throw "ActionController::UnknownFormat " error

I am trying to implement a search method that will automaticaly populate a form through the use of Ajax.
I have a simple_form_form that is feed with a collection of Client instance. Once I select a client, a js code submit the form and then goes to the corresponded controller method.
This part is working, but when the code hits the Client#search it stops at my "respond_to |format|" line. Stating that this is an unknown format.
I looked differents stackover posts, but I could'nt find any concrete answers.
Thanks,
here is the code:
My error:
error messages
routes.rb
Rails.application.routes.draw do
class OnlyAjaxRequest
def matches?(request)
request.xhr?
# raise
end
end
get 'search', to: 'invoices#search', as: 'search', constraint: OnlyAjaxRequest.new
end
formSubmit.js
let clientOption = document.querySelector('#search_client');
const form = document.querySelector('.search');
clientOption.addEventListener('change', (event) => {
form.submit();
})
Client Controller:
def search
if params[:search]
#client_found = Client.find(params[:search][:client]) if Client.find(params[:search][:client]).present?
respond_to do |format|
#format.html {}
format.js { render :search}
end
end
end
Search.js.erb
console.log('hello');
$('#ajx-cli').html("<%= escape_javascript(render partial: 'invoices/invoice_new_partial/find_client')%>");
Client Selection Form
<%= simple_form_for :search, url: search_path, remote: true, method: :get, html: { id: :find_cli } do |f| %>
<%= f.input :client, label:"Sélectionnez un client", collection: #my_clients, label_method: :company_name, value_method: :id, include_blank: true, as: :select %>
<% end %>
Updated Form
<div id='ajx-cli'>
<%= f.fields_for :client do |client| %>
<%= render partial: "invoices/invoice_new_partial/oneoff_client",locals: {f: client, client_found: #client_found} %>
<% end %>
</div>
Also, my search action seems to be processed as html instead of js.
Logs terminal
Started GET "/search?utf8=%E2%9C%93&search%5Bclient%5D=176" for ::1 at 2020-10-17 14:15:07 +0200
Processing by InvoicesController#search as HTML
Parameters: {"utf8"=>"✓", "search"=>{"client"=>"176"}}
User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 92], ["LIMIT", 1]]
↳ /Users/utilisateur/.rvm/gems/ruby-2.6.3/gems/activerecord-5.2.3/lib/active_record/log_subscriber.rb:98
Invoice Exists (0.7ms) SELECT 1 AS one FROM "invoices" WHERE (due_date < '2020-10-17') AND "invoices"."status" != $1 LIMIT $2 [["status", 3], ["LIMIT", 1]]
↳ app/controllers/application_controller.rb:32
Invoice Update All (0.9ms) UPDATE "invoices" SET "status" = 4 WHERE (due_date < '2020-10-17') AND "invoices"."status" != $1 [["status", 3]]
↳ app/controllers/application_controller.rb:34
Client Load (0.2ms) SELECT "clients".* FROM "clients" WHERE "clients"."id" = $1 LIMIT $2 [["id", 176], ["LIMIT", 1]]
↳ app/controllers/invoices_controller.rb:56
CACHE Client Load (0.0ms) SELECT "clients".* FROM "clients" WHERE "clients"."id" = $1 LIMIT $2 [["id", 176], ["LIMIT", 1]]
↳ app/controllers/invoices_controller.rb:56
Completed 406 Not Acceptable in 9ms (ActiveRecord: 2.3ms)
ActionController::UnknownFormat (ActionController::UnknownFormat):
app/controllers/invoices_controller.rb:58:in `search'
EDIT
Trying to force format didn't work either. My request was correctly processed as JS, so I didn't have the same error, but my search.js.erb was rendered instead of being executed.
New Invoice#search
def search
if params[:search]
#client_found = Client.find(params[:search][:client]) if Client.find(params[:search][:client]).present?
respond_to do |format|
format.js { render layout: false, content_type: 'text/javascript'}
end
end
New Client Selection Form
<%= simple_form_for :search, url: search_path(format: :js), remote: true, method: :get, html: { id: :find_cli } do |f| %>
<%= render partial: "invoices/invoice_new_partial/client_selection",locals: {my_clients: #my_clients, f: f, client_found: #client_found} %>
<% end %>
Logs:
Started GET "/search.js?utf8=%E2%9C%93&search%5Bclient%5D=178" for ::1 at 2020-10-17 19:19:43 +0200
Processing by InvoicesController#search as JS
Parameters: {"utf8"=>"✓", "search"=>{"client"=>"178"}}
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 92], ["LIMIT", 1]]
↳ /Users/utilisateur/.rvm/gems/ruby-2.6.3/gems/activerecord-5.2.3/lib/active_record/log_subscriber.rb:98
Invoice Exists (0.6ms) SELECT 1 AS one FROM "invoices" WHERE (due_date < '2020-10-17') AND "invoices"."status" != $1 LIMIT $2 [["status", 3], ["LIMIT", 1]]
↳ app/controllers/application_controller.rb:32
Invoice Update All (6.5ms) UPDATE "invoices" SET "status" = 4 WHERE (due_date < '2020-10-17') AND "invoices"."status" != $1 [["status", 3]]
↳ app/controllers/application_controller.rb:34
Client Load (0.3ms) SELECT "clients".* FROM "clients" WHERE "clients"."id" = $1 LIMIT $2 [["id", 178], ["LIMIT", 1]]
↳ app/controllers/invoices_controller.rb:56
CACHE Client Load (0.1ms) SELECT "clients".* FROM "clients" WHERE "clients"."id" = $1 LIMIT $2 [["id", 178], ["LIMIT", 1]]
↳ app/controllers/invoices_controller.rb:56
Rendering invoices/search.js.erb
Rendered invoices/invoice_new_partial/_find_client.html.erb (0.5ms)
Rendered invoices/search.js.erb (2.2ms)
Completed 200 OK in 24ms (Views: 5.6ms | ActiveRecord: 7.9ms)
I couldn't wrapped my mind around why my js.erb was rendered as a plain text, instead of being executed, so I started over.
I updated my form Submit.js and it worked like a charm.
New routes.rb
post 'search', to: 'invoices#search', as: 'search'
New Client Selection form
<%= simple_form_for :search, remote: true, html: { id: :find_cli } do |f| %>
<%= render partial: "invoices/invoice_new_partial/client_selection",locals: {my_clients: #my_clients, f: f, client_found: #client_found} %>
<% end %>
New formSubmit.js
let clientOption = document.querySelector('#search_client');
const form = document.querySelector('.search');
clientOption.addEventListener('change', (event) => {
let selector = document.querySelector('#search_client')
let client = selector.options[selector.selectedIndex].value;
Rails.ajax({
type: "post",
url: `/search?utf8=✓&search%5Bclient%5D=${client}`,
headers: {
accept: '*/*',
'X-CSRF-Token': Rails.csrfToken()
}
});
});

mark_for_destruction not working on update (nested object) Rails 5.1

I have two models with nested attributes: Order and Item. Every order has multiple items.
class Order < ApplicationRecord
has_many :items, autosave: true
accepts_nested_attributes_for :items,
:allow_destroy => true
end
class Item < ApplicationRecord
belongs_to :order
end
I have a setter method on the Order model to handle operations like update Item attributes, Create new Items, Delete Item, via the Orders views and Controller.
Everything works except for deleting an Item.
I would like to delete an Item when the User enters the :quantity as 0.
This is part of the Instance Setter Method with the logic that handles what I am trying to accomplish (Delete item on the edit order view (update order on controller) when the user enters 0 as the quantity).
elsif item[:id].present? && item[:qty].to_i <= 0
order_item = self.items.find item[:id]
order_item.mark_for_destruction
if I print order_item.marked_for_destruction? at the end of the elsif, I get true!... The problem is that the order gets successfully updated, but the Item stays there with the previous Quantity.
** UPDATE **
This is the whole setter method on the Order model. This instance method will update item (from Edit Order view), Destroy Item (when Qty = 0), and Create Item (from New Order view) on that order.
def items=(items=[])
items.select {|item| item[:id].present? || item[:qty].to_i.positive? }.each do |item|
if item[:id].present? && item[:qty].to_i.positive?
order_item = self.items.find item[:id]
order_item.update quantity: item[:qty],
unit: item[:unit],
catch_weight_data: item[:catch_weight_data],
elsif item[:id].present? && item[:qty].to_i <= 0
order_item = self.items.find item[:id]
order_item.mark_for_destruction
puts "Was the item marked for destruction?"
puts order_item.marked_for_destruction?
else
next unless item[:qty].to_i.positive?
lp = LabeledProduct.find item[:labeled_product_id]
order_item = self.items.new unit_price_in_cents: lp.price_in_cents,
case_price_in_cents: lp.case_price_in_cents,
data: lp.data,
quantity: item[:qty],
unit: item[:unit],
labeled_product_id: item[:labeled_product_id],
customer_labeled_product_id: item[:customer_labeled_product_id],
taxable: item[:taxable],
item_weight: item[:item_weight]
end
end
end
This is the server log ... I printed Was the Item marked for destruction? and order_item.marked_for_destruction? right after the method that updates items with qty = 0... as you can see it prints as true:
Started PATCH "/admin/customers/customer/orders/113" for 127.0.0.1 at
2018-07-19 10:26:53 -0700
Processing by Admin::Customer::OrdersController#update as HTML
Parameters: {"utf8"=>"✓","authenticity_token"=>"", "order"=>
{"status"=>"Submitted", "picked_at"=>"", "fulfilled_at"=>"", "items_attributes"=>{"0"=>{"taxable"=>"1", "unit_price"=>"2.47", "id"=>"307"}}, "items"=>[{"id"=>"307", **"qty"=>"0"**, "unit"=>"UNIT", "catch_weight_data"=>["", ""]}...
"commit"=>"Update Order", "customer_id"=>"customer", "id"=>"113"}
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 1], ["LIMIT", 1]]
Customer Load (0.3ms) SELECT "customers".* FROM "customers" WHERE "customers"."slug" = $1 LIMIT $2 [["slug", "customer"], ["LIMIT", 1]]
Order Load (0.5ms) SELECT "orders".* FROM "orders" WHERE "orders"."customer_id" = $1 AND "orders"."id" = $2 ORDER BY "orders"."created_at" DESC LIMIT $3 [["customer_id", 1], ["id", 113], ["LIMIT", 1]]
(0.2ms) BEGIN
Item Load (0.4ms) SELECT "items".* FROM "items" WHERE "items"."order_id" = $1 AND "items"."id" = $2 LIMIT $3 [["order_id", 113], ["id", 307], ["LIMIT", 1]]
Warehouse Load (0.2ms) SELECT "warehouses".* FROM "warehouses"
INNER JOIN "labeled_products" ON "warehouses"."id" =
"labeled_products"."warehouse_id" WHERE "labeled_products"."id"
= $1 LIMIT $2 [["id", 22215], ["LIMIT", 1]]
Was the item marked for destruction?
true
Item Load (0.4ms) SELECT "items".* FROM "items" WHERE
"items"."order_id" = $1 AND "items"."id" = 307 [["order_id",113]]
(0.2ms) COMMIT
Redirected to
http://localhost:3000/admin/customers/customer/orders/113
Completed 302 Found in 30ms (ActiveRecord: 2.4ms)
Controller Action:
def update
respond_to do |format|
if #order.update(order_params)
format.html { redirect_to [:admin, #customer, #order], notice: "Order was successfully updated." }
format.json { render :show, status: :ok, location: [:admin, #customer, #order] }
else
format.html { render :edit }
format.json { render json: #order.errors, status: :unprocessable_entity }
end
end
end
Some guidance will be appreciated.
Thank you!

Can't get the value stored when updating attributes

I am trying to do a marking system for moderators, in which they can select each item as "editor pick".
I've added a :editor_pick column to photos table(boolean)
and added a form in the partial for each item to have a checkbox in it:
<% if controller_name == "photos" %>
<%= simple_form_for [#user, #photo] do |f| %>
<%= f.input :editor_pick, label: "Portada" %>
<%= f.submit "Pick" %>
<% end %>
<% end %>
after that, I required the new param in strong parameters in photos controller
It's redirecting me correctly after the update, but it's not saving the new value.
When I reload the page, the boolean is still false.
My controller actions:
def by_zone
#photo = Photo.find_by(params[:id])
#user = #photo.user
render :index
end
def update
#photo = Photo.friendly.find(params[:id])
if #photo.update_attributes(photo_params)
redirect_to [current_user, #photo], notice: 'El spot se ha actualizado.'
else
render 'edit'
end
end
Edit
def photo_params
params.require(:photo).permit(:editor_pick,:url,:remote_photo_url,:thumbnail_cache ,:order,:string_tags,:tag_list, :sponsored, :photo, :terms, :title,:description,:category_id,:zone_id, :crop_x, :crop_y, :crop_w, :crop_h, sponsors_attributes: [:name, :description, :web, :facebook, :twitter, :sponsored_avatar])
end
Params Edit
Started PATCH "/users/enrique-isasi-12/photos/rustic-plastic-table" for 127.0.0.1 at 2015-01-14 16:43:55 +0100
Processing by PhotosController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"wB2SmOT0zR0dwIIguRhzFdctY51LX333CzGYelxS4Hs=", "photo"=>{"editor_pick"=>"1"}, "commit"=>"Pick", "user_id"=>"enrique-isasi-12", "id"=>"rustic-plastic-table"}
User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = 5 ORDER BY "users"."id" ASC LIMIT 1
Notification Load (0.3ms) SELECT "notifications".* FROM "notifications" WHERE "notifications"."user_id" = $1 AND "notifications"."viewed_at" IS NULL ORDER BY "notifications"."created_at" DESC LIMIT 30 [["user_id", 5]]
Notification Load (0.2ms) SELECT "notifications".* FROM "notifications" WHERE "notifications"."user_id" = $1 AND (viewed_at IS NOT NULL) ORDER BY "notifications"."created_at" DESC LIMIT 30 [["user_id", 5]]
Photo Load (0.4ms) SELECT "photos".* FROM "photos" WHERE "photos"."slug" = 'rustic-plastic-table' ORDER BY "photos"."id" ASC LIMIT 1
(0.4ms) BEGIN
Category Load (0.3ms) SELECT "categories".* FROM "categories" WHERE "categories"."id" = $1 ORDER BY "categories"."id" ASC LIMIT 1 [["id", 2]]
Zone Load (0.3ms) SELECT "zones".* FROM "zones" WHERE "zones"."id" = $1 ORDER BY "zones"."id" ASC LIMIT 1 [["id", 6]]
ActsAsTaggableOn::Tag Load (0.2ms) SELECT "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."taggable_id" = $1 AND "taggings"."taggable_type" = $2 AND (taggings.context = 'tags' AND taggings.tagger_id IS NULL) [["taggable_id", 26], ["taggable_type", "Photo"]]
SQL (0.6ms) UPDATE "photos" SET "editor_pick" = $1, "updated_at" = $2 WHERE "photos"."id" = 26 [["editor_pick", true], ["updated_at", Wed, 14 Jan 2015 15:43:55 UTC +00:00]]
false ActsAsTaggableOn::Tag Load (0.2ms) SELECT "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."taggable_id" = $1 AND "taggings"."taggable_type" = $2 AND (taggings.context = 'tags' AND taggings.tagger_id IS NULL) [["taggable_id", 26], ["taggable_type", "Photo"]]
(6.1ms) COMMIT
Redirected to http://localhost:3000/users/enrique-isasi-4/photos/rustic-plastic-table
Completed 302 Found in 31ms (ActiveRecord: 9.7ms)

Rails 4 object not saving when rendering form in another model

I have a Call model nested under Contact, a Contact has many calls. In the Edit#Contact view, I'm rendering the form to create a new call. When I submit the form, params are getting submitted, but the new Call object is not saved.
Note that if I just create a new Call from the New#Call view (form not rendered in Edit#Contact view), then the Call object is saved, so it's only a problem when rendering the form in the Edit Contact view.
console output:
Started PATCH "/contacts/54" for 127.0.0.1 at 2014-12-30 15:29:05 -0500
Processing by ContactsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"wyo0S3G5NHdfFr3e2DFw/ArhA7ouKdljCP5XaHMQ5Gc=", "contact"=>{"name"=>"Sample User 3", "entity"=>"Company 3", "phone"=>"888-888-8888", "alt_phone"=>"", "dead_phone"=>"", "email"=>"sample3#example.com", "alt_email"=>"", "dead_email"=>"", "body"=>""}, "call"=>{"dial_id"=>"1", "conversation_id"=>"1", "investing_id"=>"1", "timing_id"=>"1", "motivator_id"=>"1"}, "commit"=>"Save", "id"=>"54"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1
Contact Load (0.1ms) SELECT "contacts".* FROM "contacts" WHERE "contacts"."id" = ? ORDER BY updated_at DESC LIMIT 1 [["id", 54]]
(0.1ms) begin transaction
(0.1ms) commit transaction
Contact Store (725.1ms) {"id":54,"exception":["Elasticsearch::Transport::Transport::Errors::NotFound","[404] {\"error\":\"IndexMissingException[[contacts_development] missing]\",\"status\":404}"]}
[404] {"error":"IndexMissingException[[contacts_development] missing]","status":404}
Contact Load (0.5ms) SELECT "contacts".* FROM "contacts" WHERE "contacts"."user_id" = ? AND (id < 54) ORDER BY updated_at DESC LIMIT 1 [["user_id", 1]]
Property Load (0.2ms) SELECT "properties".* FROM "properties" WHERE "properties"."contact_id" = ? [["contact_id", 54]]
CACHE (0.0ms) SELECT "contacts".* FROM "contacts" WHERE "contacts"."id" = ? ORDER BY updated_at DESC LIMIT 1 [["id", "54"]]
CACHE (0.0ms) SELECT "contacts".* FROM "contacts" WHERE "contacts"."id" = ? ORDER BY updated_at DESC LIMIT 1 [["id", "54"]]
Dial Load (0.2ms) SELECT "dials".* FROM "dials"
Conversation Load (0.2ms) SELECT "conversations".* FROM "conversations"
Investing Load (0.2ms) SELECT "investings".* FROM "investings"
Timing Load (0.1ms) SELECT "timings".* FROM "timings"
Motivator Load (0.1ms) SELECT "motivators".* FROM "motivators"
Rendered calls/_form.html.haml (11.9ms)
Contact Load (0.5ms) SELECT "contacts".* FROM "contacts" ORDER BY updated_at DESC LIMIT 1
Contact Load (0.4ms) SELECT "contacts".* FROM "contacts" WHERE "contacts"."user_id" = ? ORDER BY updated_at ASC LIMIT 1 [["user_id", 1]]
Rendered contacts/edit.html.haml within layouts/application (29.7ms)
Contact Load (0.5ms) SELECT "contacts".* FROM "contacts" WHERE "contacts"."user_id" = ? ORDER BY updated_at DESC LIMIT 1 [["user_id", 1]]
CACHE (0.0ms) SELECT "contacts".* FROM "contacts" WHERE "contacts"."user_id" = ? ORDER BY updated_at DESC LIMIT 1 [["user_id", 1]]
Completed 200 OK in 1039ms (Views: 304.1ms | Searchkick: 725.1ms | ActiveRecord: 3.6ms)
Here is the updated form partial, rendered in contact#edit:
= form_for [Contact.find(params[:id]), Contact.find(params[:id]).calls.new], :url => url_for(controller: "Call", action: "create") do |f|
.form-group
= f.label :dial
= f.select :dial_id, options_from_collection_for_select(Dial.all, "id", "result"), class: 'form-control'
.form-group
= f.label :conversation
= f.select :conversation_id, options_from_collection_for_select(Conversation.all, "id", "result")
.form-group
= f.label :investing
= f.select :investing_id, options_from_collection_for_select(Investing.all, "id", "result")
.form-group
= f.label :timing
= f.select :timing_id, options_from_collection_for_select(Timing.all, "id", "result")
.form-group
= f.label :motivator
= f.select :motivator_id, options_from_collection_for_select(Motivator.all, "id", "result")
.actions
= f.submit 'Save', class: 'btn btn-success btn-sm'
Rendering the new call form in contact#edit view like this:
= render 'calls/form'
As a side question, I wasn't able to figure out the form_for path for this. So to tackle one problem at a time, I just have the very wordy path as a placeholder.
Here is the edit method in the Contacts Controller:
def edit
#contact = Contact.find(params[:id])
#user = #contact.user
#new_call = #contact.calls.build
authorize #contact
end
create method in the Call Controller:
def create
#contact = Contact.find(params[:contact_id])
#call = Call.new(call_params)
#call.contact_id = #contact.id
#call.user_id = current_user.id
if #call.save
flash[:notice] = "Your Call was successfully posted."
redirect_to edit_contact_path(#contact)
else
flash[:error] = "Your Call was not posted. Please try again."
redirect_to edit_contact_path(#contact)
end
end
routes.rb:
resources :contacts do
resources :properties
resources :calls
collection do
post :import
get :database
end
end

Some searches don't work

I would like to set up three search forms but the two(name and place) of the three don't work. I don't understand why it makes them different because the codes for them are almost the same.
☆members_controller
def index
if !checklogin? then return end #
if params[:name].present?
#members = Member.where("name like ?" , "%" + params[:name] + "%")
else
#members = Member.all
end
if params[:place].present?
#members = Member.where("place like ?" , "%" + params[:place] + "%")
else
#members = Member.all
end
if params[:field].present?
#members = Member.where("field like ?" , "%" + params[:field] + "%")
else
#members = Member.all
end
respond_to do |format|
format.html # index.html.erb
format.json
end
end
☆members_index(view)
<div class= "form_index">
<%= form_tag({:action=>"index"}, {:method=>"get"}) do %>
<div class="from_field_index">
<%= label_tag 'name', '名前検索:' %>
<%= text_field_tag 'name' %>
<%= submit_tag '検索' %>
<% end %>
</div>
</div>
<div class= "form_index">
<%= form_tag({:action=>"index"}, {:method=>"get"}) do %>
<div class="from_field_index">
<%= label_tag 'place', '活動場所検索:' %>
<%= text_field_tag 'place' %>
<%= submit_tag '検索' %>
<% end %>
</div>
</div>
<div class= "form_index">
<%= form_tag({:action=>"index"}, {:method=>"get"}) do %>
<div class="form_field_index">
<%= label_tag 'field', '言語分野検索:' %>
<%= text_field_tag 'field' %>
<%= submit_tag '検索' %>
<% end %>
</div>
</div>
☆command-field search
Processing by MembersController#index as HTML
Parameters: {"utf8"=>"✓", "field"=>"rails", "commit"=>"検索"}
Member Load (0.4ms) SELECT "members".* FROM "members"
CACHE (0.0ms) SELECT "members".* FROM "members"
Member Load (0.2ms) SELECT "members".* FROM "members" WHERE (field like '%rails%')
Member Load (0.1ms) SELECT "members".* FROM "members" WHERE "members"."id" = ? LIMIT 1 [["id", 17]]
CACHE (0.0ms) SELECT "members".* FROM "members" WHERE "members"."id" = ? LIMIT 1 [["id", 17]]
CACHE (0.0ms) SELECT "members".* FROM "members" WHERE "members"."id" = ? LIMIT 1 [["id", 17]]
Rendered members/index.html.erb within layouts/application (3.7ms)
CACHE (0.0ms) SELECT "members".* FROM "members" WHERE "members"."id" = ? LIMIT 1 [["id", 17]]
☆command-place search(bad case)
Started GET "/members?utf8=%E2%9C%93&place=%E6%A8%AA%E6%B5%9C&commit=%E6%A4%9C%E7%B4%A2" for 127.0.0.1 at 2013-12-03 13:47:20 +0900
Processing by MembersController#index as HTML
Parameters: {"utf8"=>"✓", "place"=>"横浜", "commit"=>"検索"}
Member Load (0.2ms) SELECT "members".* FROM "members"
CACHE (0.0ms) SELECT "members".* FROM "members"
Member Load (0.2ms) SELECT "members".* FROM "members" WHERE "members"."id" = ? LIMIT 1 [["id", 17]]
CACHE (0.0ms) SELECT "members".* FROM "members" WHERE "members"."id" = ? LIMIT 1 [["id", 17]]
CACHE (0.0ms) SELECT "members".* FROM "members" WHERE "members"."id" = ? LIMIT 1 [["id", 17]]
CACHE (0.0ms) SELECT "members".* FROM "members" WHERE "members"."id" = ? LIMIT 1 [["id", 17]]
CACHE (0.0ms) SELECT "members".* FROM "members" WHERE "members"."id" = ? LIMIT 1 [["id", 17]]
CACHE (0.0ms) SELECT "members".* FROM "members" WHERE "members"."id" = ? LIMIT 1 [["id", 17]]
CACHE (0.0ms) SELECT "members".* FROM "members" WHERE "members"."id" = ? LIMIT 1 [["id", 17]]
CACHE (0.0ms) SELECT "members".* FROM "members" WHERE "members"."id" = ? LIMIT 1 [["id", 17]]
CACHE (0.0ms) SELECT "members".* FROM "members" WHERE "members"."id" = ? LIMIT 1 [["id", 17]]
CACHE (0.0ms) SELECT "members".* FROM "members" WHERE "members"."id" = ? LIMIT 1 [["id", 17]]
Rendered members/index.html.erb within layouts/application (6.5ms)
CACHE (0.0ms) SELECT "members".* FROM "members" WHERE "members"."id" = ? LIMIT 1 [["id", 17]]
Rendered layouts/_header.html.erb (1.6ms)
Rendered layouts/_footer.html.erb (0.1ms)
Completed 200 OK in 96ms (Views: 73.5ms | ActiveRecord: 1.1ms)
I think what you need is to preserve #members:
# Rails 4
#members = Member.all
# Rails 3
#members = Member.scoped
if params[:name].present?
#members = #members.where("name like ?" , "%" + params[:name] + "%")
end
if params[:place].present?
#members = #members.where("place like ?" , "%" + params[:place] + "%")
end
if params[:field].present?
#members = #members.where("field like ?" , "%" + params[:field] + "%")
end
Note there is just one call to all. Note also that in Rails 4 you would use all, while in Rails 3 you would use scoped.

Resources