I built a feature in my app to allow users to search for images that would search the image description,member who uploaded it, and image tags but I have this weird issue where if I search for the name 'jason' it breaks, but a name like 'jesse' works just fine.
Here is my controller
def search_results
#tattoos = Tattoo.where("description LIKE ?", "%#{params[:search]}%") | Tattoo.tagged_with("#{params[:search]}", :any => true ) | Member.where("membername LIKE ?", "%#{params[:search]}%").order("created_at DESC").page(params[:page]).per(10)
end
if i search for 'jason' my app breaks, giving me an 'undefined method' error and the console shows a bunch of stuff not shown if I searched for say, 'jesse'. Im not entirely sure how to word that but here is what I mean.
Search - Jason
Started GET "/search_results?utf8=%E2%9C%93&search=jason&commit=search" for 127.0.0.1 at 2012-05-23 20:48:26 -0400
Processing by IndexController#search_results as HTML
Parameters: {"utf8"=>"✓", "search"=>"jason", "commit"=>"search"}
SQL (0.7ms) SHOW TABLES
ActsAsTaggableOn::Tag Load (0.3ms) SELECT `tags`.* FROM `tags` WHERE (name LIKE 'jason')
Tattoo Load (0.2ms) SELECT `tattoos`.* FROM `tattoos` WHERE (description LIKE '%jason%')
Tattoo Load (0.2ms) SELECT `tattoos`.* FROM `tattoos` WHERE (1 = 0)
SQL (0.7ms) SHOW TABLES
SQL (0.5ms) SHOW TABLES
Member Load (0.3ms) SELECT `members`.* FROM `members` WHERE (membername LIKE '%jason%') ORDER BY fullname asc, created_at DESC LIMIT 10 OFFSET 0
Member Load (0.3ms) SELECT `members`.* FROM `members` WHERE `members`.`id` = 7 ORDER BY fullname asc LIMIT 1
ActsAsTaggableOn::Tag Load (0.3ms) SELECT `tags`.* FROM `tags` INNER JOIN `taggings` ON `tags`.id = `taggings`.tag_id WHERE ((`taggings`.taggable_id = 43) AND (`taggings`.taggable_type = 'Tattoo')) AND (taggings.context = 'styles' AND taggings.tagger_id IS NULL)
Rendered shared/_image_roll.html.erb (27.5ms)
Rendered index/search_results.html.erb within layouts/application (29.3ms)
Completed 500 Internal Server Error in 523ms
Processing by ErrorsController#internal_server_error as HTML
Parameters: {"utf8"=>"✓", "search"=>"jason", "commit"=>"search"}
SQL (0.7ms) SHOW TABLES
SQL (0.5ms) SHOW TABLES
Rendered shared/_register.html.erb (483.4ms)
Member Load (0.2ms) SELECT `members`.* FROM `members` WHERE `members`.`id` = 7 ORDER BY fullname asc LIMIT 1
MemberRole Load (0.2ms) SELECT `member_roles`.* FROM `member_roles` WHERE (`member_roles`.member_id = 7) LIMIT 1
SQL (0.6ms) SHOW TABLES
SQL (0.4ms) SELECT COUNT(*) FROM `tattoos` WHERE `tattoos`.`status` = 'pending'
SQL (0.2ms) SELECT COUNT(*) FROM `feedbacks` WHERE `feedbacks`.`approved` = 0
SQL (0.1ms) SELECT COUNT(*) FROM `tattoos` WHERE `tattoos`.`status` = 'reported'
Rendered shared/_navbar.html.erb (87.6ms)
Rendered shared/_login_form.html.erb (2.9ms)
Rendered errors/internal_server_error.html.erb within layouts/application (582.4ms)
Completed 500 Internal Server Error in 587ms (Views: 583.9ms | ActiveRecord: 3.5ms)
ActionView::Template::Error (undefined method `member' for #<Member:0x007f0b0ca077b0>):
1: <ol class="image_roll">
2: <% #tattoos.each do |t| %>
3: <li>
4: <% unless t.member.nil? %>
5:
6: <%= link_to image_tag(t.file.url(:small),:alt=>"#{strip_tags(t.description)}, #{t.style_list}, tattoos"), member_tattoo_path(t.member, t)%>
7: <% else %>
app/views/shared/_image_roll.html.erb:4:in `block in _app_views_shared__image_roll_html_erb__3185787815883689760_69842755443480_3152220748446100192'
app/views/shared/_image_roll.html.erb:2:in `each'
app/views/shared/_image_roll.html.erb:2:in `_app_views_shared__image_roll_html_erb__3185787815883689760_69842755443480_3152220748446100192'
app/views/index/search_results.html.erb:10:in `_app_views_index_search_results_html_erb___3497910042066847338_69842586729040__4333294961394575926'
Search - Jesse:
Started GET "/search_results?utf8=%E2%9C%93&search=jesse&commit=search" for 127.0.0.1 at 2012-05-23 20:48:36 -0400
Processing by IndexController#search_results as HTML
Parameters: {"utf8"=>"✓", "search"=>"jesse", "commit"=>"search"}
ActsAsTaggableOn::Tag Load (0.6ms) SELECT `tags`.* FROM `tags` WHERE (name LIKE 'jesse')
Tattoo Load (0.7ms) SELECT `tattoos`.* FROM `tattoos` WHERE (description LIKE '%jesse%')
Tattoo Load (0.1ms) SELECT `tattoos`.* FROM `tattoos` WHERE (1 = 0)
Member Load (0.5ms) SELECT `members`.* FROM `members` WHERE (membername LIKE '%jesse%') ORDER BY fullname asc, created_at DESC LIMIT 10 OFFSET 0
Rendered shared/_search.html.erb (0.8ms)
ActsAsTaggableOn::Tag Load (0.2ms) SELECT tags.*, taggings.tags_count AS count FROM `tags` JOIN (SELECT taggings.tag_id, COUNT(taggings.tag_id) AS tags_count FROM `taggings` INNER JOIN tattoos ON tattoos.id = taggings.taggable_id WHERE (taggings.taggable_type = 'Tattoo' AND taggings.context = 'styles') AND (taggings.taggable_id IN(SELECT tattoos.id FROM `tattoos`)) GROUP BY taggings.tag_id HAVING COUNT(taggings.tag_id) > 0) AS taggings ON taggings.tag_id = tags.id ORDER BY count DESC LIMIT 40
Rendered index/_tags_list.html.erb (19.7ms)
Rendered layouts/shared/_right_column_std.html.erb (22.3ms)
Rendered shared/_register.html.erb (5.7ms)
Member Load (0.3ms) SELECT `members`.* FROM `members` WHERE `members`.`id` = 7 ORDER BY fullname asc LIMIT 1
MemberRole Load (0.1ms) SELECT `member_roles`.* FROM `member_roles` WHERE (`member_roles`.member_id = 7) LIMIT 1
SQL (0.2ms) SELECT COUNT(*) FROM `tattoos` WHERE `tattoos`.`status` = 'pending'
SQL (0.1ms) SELECT COUNT(*) FROM `feedbacks` WHERE `feedbacks`.`approved` = 0
SQL (0.1ms) SELECT COUNT(*) FROM `tattoos` WHERE `tattoos`.`status` = 'reported'
Rendered shared/_navbar.html.erb (13.5ms)
Rendered shared/_login_form.html.erb (2.9ms)
Rendered index/search_results.html.erb within layouts/application (54.3ms)
Completed 200 OK in 64ms (Views: 57.9ms | ActiveRecord: 3.0ms)
And the view:
<% #tattoos.each do |t| %>
<% unless t.member.nil? %>
<%= link_to image_tag(t.file.url(:small),:alt=>"#{strip_tags(t.description)}, #{t.style_list}, tattoos"), member_tattoo_path(t.member, t)%>
<% else %>
<%= link_to image_tag(t.file.url(:small),:alt=>"#{strip_tags(t.description)}, #{t.style_list}, tattoos"), tattoo_path(t) %>
<% end %>
<% end %>
The "| vs ||" issue is not your problem. Doing this:
Tattoo.where(...) | Tattoo.tagged_with(...) | Member.where(...)
will result in an array that is the union of the three input results. Switching to ||:
Tattoo.where(...) || Tattoo.tagged_with(...) || Member.where(...)
will just give you Tattoo.where(...) since that query will never be false or nil and the || will short circuit as soon as it has non-falsey result; Tattoo.where(...) might might be empty but empty and falsey are different things.
Your problem is that you're mixing two different things in one array: Tattoo instances from the first two queries and Member instances from the last query. Then your ERB assumes that everything in #tattoos is a Tattoo (or something else that responds to member):
<% #tattoos.each do |t| %>
<% unless t.member.nil? %>
If your Member.where(...) finds anything, then you will have at least one Member instance in #tattoos and there is no Member#member method as the error message indicates:
ActionView::Template::Error (undefined method `member' for #<Member:0x007f0b0ca077b0>):
Stop mixing two different classes in #tattoos and your problem should go away. Or you could rename it to, say, #matches and smarten up your view logic to be able to display both Tattoo and Member instances.
One thing I noticed is that you are using | instead of || in
#tattoos = Tattoo.where("description LIKE ?", "%#{params[:search]}%") | Tattoo.tagged_with("#{params[:search]}", :any => true ) | Member.where("membername LIKE ?", "%#{params[:search]}%").order("created_at DESC").page(params[:page]).per(10)
perhaps that might be part of the issue?
I would also argue that you should move this logic into the model, which should make it easier to test.
# Controller
#search_results = Tattoo.results_for_search(params[:search])
#search_results << Member.results_for_search(params[:search])
# Tattoo Model
def results_for_search(search_term)
results = where("description LIKE ?", search_term).all
results << tagged_with(search_term, :any => true)
end
# Member Model
def results_for_search(search_term)
where("membername LIKE ?", search_term).order("created_at DESC")
end
# Search Results View
<% #search_results.each do |result| %>
<% if result.is_a?(Tattoo) %>
...
<% elsif result.is_a?(Member) %>
...
<% end %>
<% end %>
Related
I'm trying to use the pg_search gem in my rails application to search through numerous models from one search bar.
I have added the search bar:
<div id="search-bar">
<%= form_tag searches_path, method: :get do %>
<span><%= text_field_tag :query, params[:query] %><%= submit_tag "Search", name: nil %></span>
<% end %>
</div>
The route:
resources :searches
The searches controller index method:
def index
#results = PgSearch.multisearch(:query)
end
And the search index.html.erb:
<ul>
<% #results.each do |result| %>
<li><%= link_to result.searchable.title, result.searchable %></li>
<% end %>
</ul>
Each model that I want to be searchable has something like this in it:
include PgSearch
multisearchable :against => [:content, :author]
And I have an initializer like this:
PgSearch.multisearch_options = {
:using => {
:tsearch => {
:dictionary => "english"
}
}
}
I created a new item to make sure that it was added to the pg_search_documents table and checked the terminal to see that it was.
Yet when I enter a search query, nothing is coming up in the results table?
Here is the terminal output from the search:
Started GET "/searches?utf8=%E2%9C%93&query=Test" for 127.0.0.1 at 2019-01-16 13:16:48 +0000
Processing by SearchesController#index as HTML
Parameters: {"utf8"=>"✓", "query"=>"Test"}
User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 1], ["LIMIT", 1]]
↳ /Users/---/.rvm/gems/ruby-2.5.3/gems/activerecord-5.2.1/lib/active_record/log_subscriber.rb:98
Group Exists (0.2ms) SELECT 1 AS one FROM "groups" LIMIT $1 [["LIMIT", 1]]
↳ app/controllers/application_controller.rb:34
Category Exists (0.2ms) SELECT 1 AS one FROM "categories" LIMIT $1 [["LIMIT", 1]]
↳ app/controllers/application_controller.rb:37
Rendering searches/index.html.erb within layouts/application
ggPgSearch::Document Load (20.6ms) SELECT "pg_search_documents".* FROM "pg_search_documents" INNER JOIN (SELECT "pg_search_documents"."id" AS pg_search_id, (ts_rank((to_tsvector('english', coalesce("pg_search_documents"."content"::text, ''))), (to_tsquery('english', ''' ' || 'query' || ' ''')), 0)) AS rank FROM "pg_search_documents" WHERE (((to_tsvector('english', coalesce("pg_search_documents"."content"::text, ''))) ## (to_tsquery('english', ''' ' || 'query' || ' '''))))) AS pg_search_ce9b9dd18c5c0023f2116f ON "pg_search_documents"."id" = pg_search_ce9b9dd18c5c0023f2116f.pg_search_id ORDER BY pg_search_ce9b9dd18c5c0023f2116f.rank DESC, "pg_search_documents"."id" ASC
↳ app/views/searches/index.html.erb:7
Rendered searches/index.html.erb within layouts/application (24.2ms)
Group Load (0.3ms) SELECT "groups".* FROM "groups"
↳ app/views/layouts/application.html.erb:59
Category Load (0.2ms) SELECT "categories".* FROM "categories"
↳ app/views/layouts/application.html.erb:72
Completed 200 OK in 114ms (Views: 88.4ms | ActiveRecord: 21.9ms)
The ul tags are present on the page, but no li items, and I am sure that the term I am putting in was within the item I created.
How come it isn't picking up any results? Many thanks
Did you do the following?
$ rails g pg_search:migration:multisearch
$ rake db:migrate
It's required for multisearching. Also existing items may not be added to the document as you already know. You would need to "rebuild" as stated in the docs. When you made a new item for testing, did you save it properly?
Here are the docs I found for the pg gem:
https://github.com/Casecommons/pg_search
I have three main Classes: Users, Vocabs and Tags. A User has many Tags. Tags has-and-belongs-to-many Vocabs (and the other way around).
How can I order a collection of Tags when getting them through a Vocab-Object?
#vocab.tag
gets the tags from the joins table, which has no created_at column.
Is there a handy way to solve this problem?
I am pretty new to Rails so excuse me if this is obvious.
EDIT: I just tried
#tags = #vocab.tags.order('tags.created_at DESC')
but without success.
The computer says:
Started GET "/users/1/vocabs/61" for 127.0.0.1 at 2014-12-11 15:41:15 +0100
Processing by VocabsController#show as HTML
Parameters: {"user_id"=>"1", "id"=>"61"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
Vocab Load (0.3ms) SELECT "vocabs".* FROM "vocabs" WHERE "vocabs"."user_id" = ? AND "vocabs"."id"
= ? ORDER BY created_at DESC LIMIT 1 [["user_id", 1], ["id", 61]]
Tag Load (0.5ms) SELECT DISTINCT "tags".* FROM "tags" INNER JOIN "tags_vocabs" ON "tags"."id" =
"tags_vocabs"."tag_id" WHERE "tags_vocabs"."vocab_id" = ? [["vocab_id", 61]]
Rendered shared/_error_messages.html.erb (0.2ms)
Rendered vocabs/show.html.erb within layouts/application (10.7ms)
Rendered layouts/_shim.html.erb (0.1ms)
Rendered layouts/_header.html.erb (1.1ms)
Completed 200 OK in 602ms (Views: 587.3ms | ActiveRecord: 1.2ms)
The controller action looks like this:
def new_tag
#user = current_user
#vocab = #user.vocabs.find(params[:id])
#tags = #vocab.tags.order('tags.created_at DESC')
#tag = current_user.tags.build(name: params[:tag])
if #tag.save
#vocab.tags<<#tag
flash.now[:success] ='Tag successfully created.'
redirect_to user_vocab_path(#user, #vocab)
else
flash.now[:danger] = "Tag could not be created!"
render :action => "show"
end
end
I'm new to both Ruby and Rails and I've inherited an existing company website that I've been modifying to hit a new job tracking site. Everything works great in development, but when I deploy to our staging server, two of my job routes begin having problems.
Before I describe in more detail, I'm using the following versions on an AWS Linux server:
Ruby 1.9.3-p392
Rails 3.2.13
Passenger 4.0.37
Apache 2.2.26
I have two routes that are causing problems: viewing a job posting and applying for the job. Sometimes the job posting shows up at both URLs and sometimes the job application shows up for both URLs, I think it ends up displaying whichever page loaded first.
The lines in routes.rb related to the jobs_controller are (comments added to explain URLs):
# Submits a general application to the company
get '/careers/apply', controller: :jobs, action: :apply, as: :apply
# Applies to a particular position
get '/career/:ref_number/apply', controller: :jobs, action: :apply, as: :apply_job
# Displays details for a particular job opening
get '/career/:ref_number', controller: :jobs, action: :show, as: :job
# Searches available job openings
get '/careers/search', controller: :jobs, action: :search, as: :job
I've tried reordering routes in the file, changing URLs so they don't overlap and changing HTTP methods and nothing has worked.
jobs_controller.rb:
require 'pagination'
require 'related'
require 'job_selector'
class JobsController < ApplicationController
include Website::Pagination
before_filter :set_page_or_redirect, only: :index
skip_authorization_check
def index
#jobs = Job.with_tag_associations.page(#page)
end
def show
#job = Job.find_by_ref_number(params[:ref_number])
related_job_finder = Website::Related.new(#job)
#related_jobs = {
tags: related_job_finder.related(Job, :tags).limit(5).to_a,
categories: related_job_finder.related(Job, :categories).limit(5).to_a,
}
#featured_jobs = Website::JobSelector.random_featured_jobs(2)
end
def search
#location = params[:location]
#query = params[:query]
#search = Job.solr_search(#query, params.slice(:location, :category, :page))
#jobs = #search.results
end
def apply
if !params[:ref_number].nil?
#job = Job.find_by_ref_number(params[:ref_number])
related_job_finder = Website::Related.new(#job)
#related_jobs = {
tags: related_job_finder.related(Job, :tags).limit(5).to_a,
categories: related_job_finder.related(Job, :categories).limit(5).to_a,
}
else
#job = Job.new(ref_number: -1,
title: 'General Application')
#related_jobs = {
tags: [],
categories: []
}
end
#featured_jobs = Website::JobSelector.random_featured_jobs(2)
end
end
My staging.log file shows the following when I viewed a job requisition, then clicked the Apply button to view the application page. According to the logs, the correct controller methods are called and the correct views/* components are loaded for each page, but - in this instance - both URLs displayed the job details and I couldn't get to the job application.
View Job Page (GET /career/70779)
Started GET "/career/70779" for 173.66.87.200 at 2014-02-27 04:04:42 +0000
Processing by JobsController#show as HTML
Parameters: {"ref_number"=>"70779"}
Job Load (0.5ms) SELECT `jobs`.* FROM `jobs` WHERE `jobs`.`ref_number` = 70779 LIMIT 1
ActsAsTaggableOn::Tag Load (0.5ms) SELECT `tags`.* FROM `tags` INNER JOIN `taggings` ON `tags`.`id` = `taggings`.`tag_id` WHERE `taggings`.`taggable_id` = 261 AND `taggings`.`taggable_type` = 'Job' AND (taggings.context = 'tags' AND taggings.tagger_id IS NULL)
Job Load (1.5ms) SELECT jobs.*, COUNT(tags.id) AS count FROM jobs, tags, taggings WHERE (jobs.id != 261 AND jobs.id = taggings.taggable_id AND taggings.taggable_type = 'Job' AND taggings.tag_id = tags.id AND tags.name IN (NULL)) GROUP BY jobs.id ORDER BY count DESC LIMIT 5
ActsAsTaggableOn::Tag Load (0.3ms) SELECT `tags`.* FROM `tags` INNER JOIN `taggings` ON `tags`.`id` = `taggings`.`tag_id` WHERE `taggings`.`taggable_id` = 261 AND `taggings`.`taggable_type` = 'Job' AND (taggings.context = 'categories' AND taggings.tagger_id IS NULL)
CACHE (0.0ms) SELECT jobs.*, COUNT(tags.id) AS count FROM jobs, tags, taggings WHERE (jobs.id != 261 AND jobs.id = taggings.taggable_id AND taggings.taggable_type = 'Job' AND taggings.tag_id = tags.id AND tags.name IN (NULL)) GROUP BY jobs.id ORDER BY count DESC LIMIT 5
(24.7ms) SELECT COUNT(*) FROM `tags` INNER JOIN `taggings` ON `tags`.`id` = `taggings`.`tag_id` WHERE `taggings`.`taggable_id` = 261 AND `taggings`.`taggable_type` = 'Job' AND (taggings.context = 'primary_category')
ActsAsTaggableOn::Tag Load (0.6ms) SELECT `tags`.* FROM `tags` INNER JOIN `taggings` ON `tags`.`id` = `taggings`.`tag_id` WHERE `taggings`.`taggable_id` = 261 AND `taggings`.`taggable_type` = 'Job' AND (taggings.context = 'primary_category') LIMIT 1
Read fragment views/jobs/261-20140226035339 (0.2ms)
CACHE (0.0ms) SELECT COUNT(*) FROM `tags` INNER JOIN `taggings` ON `tags`.`id` = `taggings`.`tag_id` WHERE `taggings`.`taggable_id` = 261 AND `taggings`.`taggable_type` = 'Job' AND (taggings.context = 'primary_category')
CACHE (0.0ms) SELECT `tags`.* FROM `tags` INNER JOIN `taggings` ON `tags`.`id` = `taggings`.`tag_id` WHERE `taggings`.`taggable_id` = 261 AND `taggings`.`taggable_type` = 'Job' AND (taggings.context = 'primary_category') LIMIT 1
Rendered shared/_category_label.html.erb (8.5ms)
Rendered shared/share_links/_twitter.html.erb (0.4ms)
Rendered shared/share_links/_facebook.html.erb (0.4ms)
Rendered shared/share_links/_google_plus.html.erb (0.4ms)
Rendered shared/share_links/_linkedin.html.erb (0.3ms)
Rendered jobs/_share_links.html.erb (29.6ms)
(0.4ms) SELECT COUNT(*) FROM `tags` INNER JOIN `taggings` ON `tags`.`id` = `taggings`.`tag_id` WHERE `taggings`.`taggable_id` = 261 AND `taggings`.`taggable_type` = 'Job' AND (taggings.context = 'tags')
Rendered shared/_tags.html.erb (4.6ms)
Rendered jobs/_apply_button.html.erb (1.0ms)
Read fragment views/jobs/261-20140226035339/join-us (0.1ms)
Job Load (1.4ms) SELECT `jobs`.* FROM `jobs` WHERE `jobs`.`is_featured` = 1 ORDER BY RAND() LIMIT 2
Read fragment views/jobs/263-20140226190437/sidebar (0.1ms)
Write fragment views/jobs/263-20140226190437/sidebar (4.1ms)
Read fragment views/jobs/262-20140226164039/sidebar (0.1ms)
Write fragment views/jobs/262-20140226164039/sidebar (27.2ms)
Rendered shared/_show_sidebar.html.erb (178.1ms)
Write fragment views/jobs/261-20140226035339/join-us (2.8ms)
Rendered jobs/_side_bar.html.erb (184.0ms)
Write fragment views/jobs/261-20140226035339 (2.6ms)
Rendered jobs/show.html.erb within layouts/application (386.9ms)
Rendered layouts/_head.html.erb (3.4ms)
Read fragment views/navigation (0.1ms)
Write fragment views/navigation (2.8ms)
Rendered layouts/_navigation.html.erb (5.2ms)
Rendered layouts/_context_nav.html.erb (0.6ms)
Rendered layouts/_flash_messages.html.erb (24.9ms)
Rendered layouts/_javascripts.html.erb (4.3ms)
Rendered layouts/_footer.html.erb (31.7ms)
Completed 200 OK in 1860ms (Views: 683.4ms | ActiveRecord: 34.6ms | Solr: 0.0ms)
Apply for Job Page (GET /career/70779/apply)
Started GET "/career/70779/apply" for 173.66.87.200 at 2014-02-27 04:04:56 +0000
Processing by JobsController#apply as HTML
Parameters: {"ref_number"=>"70779"}
Job Load (0.5ms) SELECT `jobs`.* FROM `jobs` WHERE `jobs`.`ref_number` = 70779 LIMIT 1
ActsAsTaggableOn::Tag Load (0.4ms) SELECT `tags`.* FROM `tags` INNER JOIN `taggings` ON `tags`.`id` = `taggings`.`tag_id` WHERE `taggings`.`taggable_id` = 261 AND `taggings`.`taggable_type` = 'Job' AND (taggings.context = 'tags' AND taggings.tagger_id IS NULL)
Job Load (1.0ms) SELECT jobs.*, COUNT(tags.id) AS count FROM jobs, tags, taggings WHERE (jobs.id != 261 AND jobs.id = taggings.taggable_id AND taggings.taggable_type = 'Job' AND taggings.tag_id = tags.id AND tags.name IN (NULL)) GROUP BY jobs.id ORDER BY count DESC LIMIT 5
ActsAsTaggableOn::Tag Load (0.3ms) SELECT `tags`.* FROM `tags` INNER JOIN `taggings` ON `tags`.`id` = `taggings`.`tag_id` WHERE `taggings`.`taggable_id` = 261 AND `taggings`.`taggable_type` = 'Job' AND (taggings.context = 'categories' AND taggings.tagger_id IS NULL)
CACHE (0.0ms) SELECT jobs.*, COUNT(tags.id) AS count FROM jobs, tags, taggings WHERE (jobs.id != 261 AND jobs.id = taggings.taggable_id AND taggings.taggable_type = 'Job' AND taggings.tag_id = tags.id AND tags.name IN (NULL)) GROUP BY jobs.id ORDER BY count DESC LIMIT 5
(0.4ms) SELECT COUNT(*) FROM `tags` INNER JOIN `taggings` ON `tags`.`id` = `taggings`.`tag_id` WHERE `taggings`.`taggable_id` = 261 AND `taggings`.`taggable_type` = 'Job' AND (taggings.context = 'primary_category')
ActsAsTaggableOn::Tag Load (0.4ms) SELECT `tags`.* FROM `tags` INNER JOIN `taggings` ON `tags`.`id` = `taggings`.`tag_id` WHERE `taggings`.`taggable_id` = 261 AND `taggings`.`taggable_type` = 'Job' AND (taggings.context = 'primary_category') LIMIT 1
Read fragment views/jobs/261-20140226035339 (0.4ms)
Rendered jobs/apply.html.erb within layouts/application (6.6ms)
Rendered layouts/_head.html.erb (130.7ms)
Read fragment views/navigation (0.3ms)
Rendered layouts/_navigation.html.erb (0.7ms)
Rendered layouts/_context_nav.html.erb (0.0ms)
Rendered layouts/_flash_messages.html.erb (0.1ms)
Rendered layouts/_javascripts.html.erb (2.6ms)
Rendered layouts/_footer.html.erb (3.5ms)
Completed 200 OK in 156ms (Views: 144.2ms | ActiveRecord: 3.1ms | Solr: 0.0ms)
My deployment script does the following:
RAILS_ENV=staging bundle exec rake db:migrate
RAILS_ENV=staging bundle exec rake assets:precompile
touch tmp/restart.txt
RAILS_ENV=staging bundle exec rake sunspot:reindex
config/environments/staging.rb:
NewWebsite::Application.configure do
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Do fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = true
# Generate digests for assets URLs
config.assets.digest = true
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Turn on memory caching (tried this after seeing some SO answers; didn't make a difference)
config.cache_store = :memory_store
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
end
One last detail. I was able to duplicate the problem locally while running RAILS_ENV=staging rails s after precompiling the assets so I don't think its related to Apache/Passenger vs local execution.
Thanks in advance!
So, I just learned a very long lesson about Rails fragment caching!
I was running into this problem because I had copied the show.html.erb file responsible for displaying job details and edited it to make the apply.html.erb file that displayed the IFRAME with the actual application. Not realizing what it was doing, I left the following line in the apply.html.erb file:
<% cache #job do %>
I've now realized that turns on Rails fragment caching, which explains all of my problems:
Caching was disabled in development and enabled in staging and production which is why this problem never showed up locally.
Since the <% cache #job do %> block was identical in both fragments, it explains why I saw the content from whichever page I hit first for any given job in both URLs.
The solution:
Removed the cache block from the application fragment since it is doing negligible processing. Rails now generates that page appropriately every time it is loaded while still caching the job details display page.
I have a next button that is working great, but previous button just does not want to play nice. Funny thing is that I've tried to build this a few different ways referencing methods on SO and elsewhere, but previous always goes to the earliest record...
In my submission model:
def previous
self.class.first(:conditions => ["created_at < ?", created_at], :order => "created_at asc")
end
def next
self.class.first(:conditions => ["created_at > ?", created_at], :order => "created_at asc")
end
And in my view:
<% if #submission.previous %>
<%= link_to "previous", contest_submission_path(#contest, #submission.previous),
:class => 'pull-left btn btn-large' %>
<% end %>
<% if #submission.next %>
<%= link_to "next", contest_submission_path(#contest, #submission.next),
:class => 'pull-right btn btn-large' %>
<% end %>
Like I said, next works great, but previous returns to the earliest record. I'm nearing wits end with this one. Anybody have an answer?
EDITED
Logs:
Started GET "/contests/1/submissions/1" for 127.0.0.1 at 2012-11-30 08:08:52 -0800
Processing by SubmissionsController#show as HTML
Parameters: {"contest_id"=>"1", "id"=>"1"}
User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = 2 ORDER BY users.created_at DESC LIMIT 1
Contest Load (0.3ms) SELECT "contests".* FROM "contests" WHERE "contests"."id" = $1 LIMIT 1 [["id", "1"]]
Submission Load (0.2ms) SELECT "submissions".* FROM "submissions" WHERE "submissions"."id" = $1 ORDER BY submissions.created_at ASC LIMIT 1 [["id", "1"]]
CACHE (0.0ms) SELECT "submissions".* FROM "submissions" WHERE "submissions"."id" = $1 ORDER BY submissions.created_at ASC LIMIT 1 [["id", "1"]]
Comment Load (0.4ms) SELECT "comments".* FROM "comments" WHERE "comments"."commentable_id" = 1 AND "comments"."commentable_type" = 'Submission' ORDER BY comments.created_at DESC, created_at
Submission Load (0.3ms) SELECT "submissions".* FROM "submissions" WHERE (created_at < '2012-10-08 14:32:40.590930') ORDER BY submissions.created_at ASC, created_at asc LIMIT 1
Submission Load (0.2ms) SELECT "submissions".* FROM "submissions" WHERE (created_at > '2012-10-08 14:32:40.590930') ORDER BY submissions.created_at ASC, created_at asc LIMIT 1
CACHE (0.0ms) SELECT "submissions".* FROM "submissions" WHERE (created_at > '2012-10-08 14:32:40.590930') ORDER BY submissions.created_at ASC, created_at asc LIMIT 1
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = 2 ORDER BY users.created_at DESC LIMIT 1
Image Load (0.2ms) SELECT "images".* FROM "images" WHERE "images"."parent_id" = 2 AND "images"."parent_type" = 'User' LIMIT 1
Rendered submissions/_follow_unfollow.html.erb (0.1ms)
Image Load (0.4ms) SELECT "images".* FROM "images" WHERE "images"."parent_id" = 1 AND "images"."parent_type" = 'Submission' LIMIT 1
Rendered submissions/_hide_comments_form.html.erb (1.9ms)
Rendered comments/_form.html.erb (2.5ms)
Rendered comments/_comment.html.erb (3.5ms)
Rendered submissions/show.html.erb within layouts/application (21.7ms)
Rendered layouts/_stylesheets.html.erb (4.3ms)
CACHE (0.0ms) SELECT "images".* FROM "images" WHERE "images"."parent_id" = 2 AND "images"."parent_type" = 'User' LIMIT 1
Role Load (0.5ms) SELECT "roles".* FROM "roles" INNER JOIN "assignments" ON "roles"."id" = "assignments"."role_id" WHERE "assignments"."user_id" = 2
Rendered layouts/_header.html.erb (4.6ms)
Rendered layouts/_footer.html.erb (0.7ms)
Completed 200 OK in 105ms (Views: 97.8ms | ActiveRecord: 3.0ms)
Log #2
Started GET "/contests/1/submissions/%23%3CActiveRecord::Relation:0x007fc3b5e50af8%3E" for 127.0.0.1 at 2012-11-30 08:43:15 -0800
Processing by SubmissionsController#show as HTML
Parameters: {"contest_id"=>"1", "id"=>"#<ActiveRecord::Relation:0x007fc3b5e50af8>"}
User Load (0.6ms) SELECT "users".* FROM "users" WHERE "users"."id" = 2 ORDER BY users.created_at DESC LIMIT 1
Contest Load (0.3ms) SELECT "contests".* FROM "contests" WHERE "contests"."id" = $1 LIMIT 1 [["id", "1"]]
Submission Load (0.3ms) SELECT "submissions".* FROM "submissions" WHERE "submissions"."id" = $1 LIMIT 1 [["id", "#<ActiveRecord::Relation:0x007fc3b5e50af8>"]]
Completed 500 Internal Server Error in 4ms
ActiveRecord::RecordNotFound (Couldn't find Submission with id=# <ActiveRecord::Relation:0x007fc3b5e50af8>):
app/controllers/submissions_controller.rb:89:in `find_submission'
Final Solution:
In submission.rb
default_scope order: 'submissions.created_at DESC'
def previous_sub
self.class.where("created_at > ?", created_at).reorder("created_at asc").first
end
def next_sub
self.class.where("created_at < ?", created_at).reorder("created_at desc").first
end
In view (show):
<% if #submission.previous_sub %>
<%= link_to "previous", contest_submission_path(#contest, #submission.previous_sub),
:class => 'pull-left btn btn-large' %>
<% end %>
<% if #submission.next_sub %>
<%= link_to "next", contest_submission_path(#contest, #submission.next_sub),
:class => 'pull-right btn btn-large' %>
<% end %>
I ended up exchanging the names of the methods, so that the show record order would match the index, which is scoped in DESC order or most recent to earliest.
Your code is correct, but your log shows
SELECT "submissions".* FROM "submissions"
WHERE (created_at < '2012-10-08 14:32:40.590930')
ORDER BY submissions.created_at ASC, created_at asc LIMIT 1
If this is a query that searches for previous, this is where it fails (because it orders the previous dates in ascending order, and takes the first - the earliest). Could it be you forgot to restart the app after making changes (though it should be reloaded automatically in dev mode)?
Or it is possible you have default_scope or some other scope that breaks the conditions. I wonder why there is submissions.created_at ASC, created_at asc - twice? Probably submissions.created_at ASC is a default scope.
I'd suggest you to use new AR query syntax, and perhaps reorder to exclude other ordering scopes:
self.class.where("created_at < ?", created_at).reorder("created_at desc").first
I'm working on the Ruby on Rails Tutorial. I have the asynchronous follow buttons working. Interestingly, each of the javascript calls is getting called twice in a row when I click the button. Any thoughts on how I make it only send one request? Here is my log
Started POST "/tag_user_relationships/123" for
127.0.0.1 at 2011-06-13 21:18:59 -0700 Processing by TagUserRelationshipsController#destroy as JS Parameters: {"utf8"=>"✓", "authenticity_token"=>"goedvibRxKtDRiAufp1ThWJP0rRBU2cMH2xp7qodKws=", "commit"=>"Unfollow", "id"=>"123"} User Load (0.2ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 2 LIMIT 1 TagUserRelationship Load (0.2ms) SELECT `tag_user_relationships`.* FROM `tag_user_relationships` WHERE `tag_user_relationships`.`id` = 123 LIMIT 1 Tag Load (0.2ms) SELECT `tags`.* FROM `tags` WHERE `tags`.`id`
= 9 LIMIT 1 TagUserRelationship Load (0.3ms) SELECT `tag_user_relationships`.* FROM `tag_user_relationships` WHERE `tag_user_relationships`.`tag_id` = 9 AND (`tag_user_relationships`.user_id
= 2) LIMIT 1 SQL (0.1ms) BEGIN AREL (0.2ms) DELETE FROM `tag_user_relationships` WHERE `tag_user_relationships`.`id` = 123 SQL (0.4ms) COMMIT SQL (0.4ms) SELECT COUNT(*) FROM `users` INNER JOIN `tag_user_relationships` ON `users`.id = `tag_user_relationships`.user_id WHERE ((`tag_user_relationships`.tag_id = 9)) SQL (0.3ms) SELECT COUNT(*) FROM `tags` INNER JOIN `tag_user_relationships` ON `tags`.id
= `tag_user_relationships`.tag_id WHERE ((`tag_user_relationships`.user_id = 2)) Rendered tag_user_relationships/_form.js.erb (15.8ms) Rendered tags/_follow.html.erb (2.1ms) Rendered tag_user_relationships/destroy.js.erb (20.3ms) Completed 200 OK in 138ms (Views: 28.1ms | ActiveRecord: 2.3ms)
Started POST "/tag_user_relationships/123" for
127.0.0.1 at 2011-06-13 21:18:59 -0700 Processing by TagUserRelationshipsController#destroy as JS Parameters: {"utf8"=>"✓", "authenticity_token"=>"goedvibRxKtDRiAufp1ThWJP0rRBU2cMH2xp7qodKws=", "id"=>"123"} User Load (0.2ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 2 LIMIT 1 TagUserRelationship Load (0.2ms) SELECT `tag_user_relationships`.* FROM `tag_user_relationships` WHERE `tag_user_relationships`.`id` = 123 LIMIT 1 Completed 404 Not Found in 70ms
ActiveRecord::RecordNotFound (Couldn't find TagUserRelationship with ID=123): app/controllers/tag_user_relationships_controller.rb:14:in `destroy'
Rendered /Users/me/.rvm/gems/ruby-1.9.2-p136#rails3tutorial/gems/actionpack-3.0.8/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.0ms) Rendered /Users/me/.rvm/gems/ruby-1.9.2-p136#rails3tutorial/gems/actionpack-3.0.8/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (153.6ms) Rendered /Users/me/.rvm/gems/ruby-1.9.2-p136#rails3tutorial/gems/actionpack-3.0.8/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (160.2ms)
And here is my view
$("#<%= "follower_info#{#tag.id}" %>").html("<%=escape_javascript(pluralize(#tag.followers.count,'follower'))%>");
var link = $('<a>').attr('href',"<%=user_tags_path(current_user) %>").text("<%= escape_javascript(pluralize(current_user.beats.count,'tag')) %>");
$("#<%= "user#{current_user.id}_following" %>").html(link); $("#<%= "follow_form#{#tag.id}" %>").html("<%= escape_javascript("#{render('tags/unfollow', :tag => #tag)}").html_safe %>");
And my controller
def create
#tag = Tag.find(params[:tag_user_relationship][:tag_id])
current_user.follow_tag!(#tag)
respond_to do |format|
format.html { redirect_to #tag }
format.js
end
end
I had this same issue recently. Is there any chance that you installed the ajax gem and also included the jquery code in the Javascripts folder? If so, the calls will be made twice.