When I point my browser at http://localhost:3000/searches, I get the following error:
Error 324 (net::ERR_EMPTY_RESPONSE): The server closed the connection without sending any data.
Why? And how do I fix this?
Relevant code below...
/config/routes.rb:
resources :searches, :only => [:index]
/app/controllers/searches_controller.rb:
class SearchesController < ApplicationController
respond_to :html
filter_access_to :all
def index
#term = params[:term]
#results = PgSearch.multisearch(#term) unless #term.blank?
redirect_to searches_path
end
end
/app/views/searches/index.html.haml:
.textbox
= render "shared/notice"
%h1 Advanced Search
= simple_form_for #searches do |f|
= f.input :term
= f.button :submit
- unless #results.blank?
- #results.each do |result|
%h3= result.searchable.header
%p= result.searchable.body
/config/authorization_rules.rb:
authorization do
role :admin do
has_permission_on [...snip... :searches], :to => [:index, :show, :new, :create, :edit, :update, :destroy, :print, :none, :audit]
end
end
/app/models/reference.rb:
class Reference < ActiveRecord::Base
has_paper_trail
include PgSearch
multisearchable :against => [:source_text, :citation]
attr_accessible :reference_ids, :question_ids
attr_accessible :url, :citation, :details, :veracity_id, :original, :source_text
has_many :footnotes
def header
self.citation
end
def body
self.details
end
end
/app/models/footnote.rb:
class Footnote < ActiveRecord::Base
has_paper_trail
include PgSearch
multisearchable :against => [:details]
attr_accessible :reference_id, :details, :page_range, :relevant
belongs_to :reference
def header
[self.reference.citation, " ", self.page_range].join
end
def body
self.details
end
end
/db/migrate/20130326110126_create_pg_search_documents.rb:
class CreatePgSearchDocuments < ActiveRecord::Migration
def self.up
say_with_time("Creating table for pg_search multisearch") do
create_table :pg_search_documents do |t|
t.text :content
t.belongs_to :searchable, :polymorphic => true
t.timestamps
end
end
end
def self.down
say_with_time("Dropping table for pg_search multisearch") do
drop_table :pg_search_documents
end
end
end
/db/migrate/20130326110723_rebuild_search_indexes.rb:
class RebuildSearchIndexes < ActiveRecord::Migration
def up
PgSearch::Multisearch.rebuild(Reference)
PgSearch::Multisearch.rebuild(Footnote)
end
def down
PgSearch::Reference.delete_all
PgSearch::Footnote.delete_all
end
end
You've got a cyclic redirect; redirect_to searches_path just sends the request back into the same action.
Try just taking the redirect_to line out. That way Rails will render app/views/searches/index.html.haml by default. Then posting to the form should request index again and produce what you want.
Related
I would like to add "category" function.
I associated article.rb and category.rb.
However, undefined method `categories' for nil:NilClass was present.
I have no idea.If you know any solution, please tell me.
Index.html.erb
<% unless #article.categories.blank? %>
<% #articles.categories.each do |category|%>
<%= link_to category.name,article_path(category_id:category.id)%>
<%end%>
<%end%>
article.rb
class Article < ApplicationRecord
scope :from_category, -> (category_id) { where(id: article_ids = ArticleCategory.where(category_id: category_id).select(:article_id))}
validates :title, presence: true
validates :content, presence: true
mount_uploader :image,ImageUploader
has_many :categories, through: :article_categories
has_many :article_categories, dependent: :destroy
def save_categories(tags)
current_tags = self.categoires.pluck(:name) unless self.categories.nil?
old_tags = current_tags - tags
new_tags = tags - current_tags
old_tags.each do |old_name|
self.categories.delete Category.find_by(name:old_name)
end
new_tags.each do |new_name|
article_category = Category.find_or_create_by(name:new_name)
self.categories << article_category
end
end
end
category.rb
class Category < ApplicationRecord
validates :name,presense: true,length:{maximum:50}
has_many :articles,through: :article_categories
has_many :article_categories,dependent: :destroy
end
article_category.rb
class ArticleCategory < ApplicationRecord
belongs_to :article
belongs_to :category
validates :article_id,presense:true
validates :category_id,presense:true
end
articles_controller.rb
class ArticlesController < ApplicationController
before_action :set_post, only: [:show,:edit,:update]
before_action :authenticate_user!, :except => [:index,:show]
before_action :set_article_tags_to_gon, only: [:edit]
def index
if params[:category_id]
#selected_category = Category.find(params[:category_id])
#articles= Article.from_category(params[:category_id]).page(params[:page])
else
#articles= Article.all.page(params[:page])
end
#articles = Article.page params[:page]
end
def show
end
def new
#article = Article.new
end
def create
#article = Article.new(article_params)
if #article.save
redirect_to articles_path
else
render 'articles/new'
end
end
def edit
#category_list = #article.categories.pluck(:name).join(",")
end
def update
if #article.update(article_params)
redirect_to articles_path
else
redirect_to 'edit'
end
end
private
def article_params
params[:article].permit(:title,:content,:image,:tag_list,:category)
end
def set_post
#article = Article.find(params[:id])
end
error message
You're calling categories on a nil object, in this case #article. Did you mean to call it on #articles?
If not, you will need to define #article in the index action of your controller.
I'm new to ruby on rails so please forgive the question. I tried following this example Rails sort tags by most used (tag.posts.count) but kept getting an error "undefined method `order' for Items:Module". I am trying to sort a list of items based on an item's likes. So an item with 5 likes should be placed above an item with only 3 likes. I have listed below all my relevant code down below. Thank you so much guys!!
Like.rb
class Like < ApplicationRecord
belongs_to :item, :counter_cache => true
belongs_to :user
end
Likes_controller.rb
class Items::LikesController < ApplicationController
before_action :authenticate_user!
before_action :set_book
def create
#item.likes.where(user_id: current_user.id).first_or_create
respond_to do |format|
format.html {redirect_to #item}
format.js
end
end
def destroy
#item.likes.where(user_id: current_user.id).destroy_all
respond_to do |format|
format.html {redirect_to #item}
format.js
end
end
private
def set_book
#item = Item.find(params[:item_id])
end
end
Item.rb
class Item < ApplicationRecord
has_many :likes, :counter_cache => true
users_controller.rb
class UsersController < ApplicationController
before_action :authenticate_user!
before_action :set_user, only: [:show, :edit, :update, :destroy]
def index
#items = Item.all
Items.order('likes_count')
end
def show
#items = Item.find(params[:id])
end
private
def set_user
#item = Item.find(params[:id])
end
end
index.html.erb
<% #items.each do |item| %>
<%= item.product %>
<div><%= image_tag(item.avatar.url(:thumb)) %></div>
<% end %>
Migrations Relevant
class AddLikecountsToItem < ActiveRecord::Migration[5.0]
def change
add_column :items, :likes_count, :integer, :null => false, :default => 0
end
end
class CreateLikes < ActiveRecord::Migration[5.0]
def change
create_table :likes do |t|
t.integer :user_id
t.integer :item_id
t.timestamps
end
end
end
in users_controller.rb
def index
#items = Item.order('likes_count')
end
I have the Teacher model, and I am using the searchkick for this model. The first problem is when I search for a particular teacher, if the teacher is in model, it will not only return that teacher but also the rest of the teachers in my model. I did some research on the internet and couldn't find the solution for my case. Therefore, I really need your help guys.
Here are some of my files, just in case you need to see them, and I think you do.
teachers_controller.rb:
class TeachersController < ApplicationController
before_action :find_school
before_action :find_teacher, only: [:show, :edit, :update, :destroy]
def show
end
def search
if params[:search].present?
#teachers = #school.teachers.search(params[:search], fields: [{fullName: :exact}])
else
#teachers = []
end
end
def new
#teacher = #school.teachers.build
end
def create
#teacher = #school.teachers.create(teacher_params)
#teacher.save
redirect_to(#school)
end
def edit
end
def update
#teacher.update(teacher_params)
redirect_to(#school)
end
private
def find_school
#school = School.find(params[:school_id])
end
def find_teacher
#teacher = Teacher.find(params[:id])
end
def teacher_params
params.require(:teacher).permit(:firstName, :lastName, :middleName, :department, :school_id)
end
end
search.html.haml:
.text-center
/ No search results announcement/notification
- if #teachers.blank?
%h2 Xin lỗi, hệ thống chúng tôi không có thông tin về giảng viên mà bạn muốn tìm.
- else
- #school.teachers.each do |teacher|
%h2= link_to teacher.to_s, school_teacher_path(#school, teacher)
%br/
.text-center
= link_to("Trang Trước", school_url(#school), class: "btn btn-default btn-xs")
= link_to("Trang Chủ", root_path, class: "btn btn-default btn-xs")
teacher.rb:
class Teacher < ActiveRecord::Base
belongs_to :school
has_many :ratings
searchkick word_start: [:firstName, :lastName, :middleName]
def name
"#{lastName} #{middleName} #{firstName}"
end
def to_s
name
end
end
routes.rb:
Rails.application.routes.draw do
devise_for :users
resources :schools do
collection do
get 'search'
end
resources :teachers do
collection do
get 'search'
end
end
end
resources :teachers do
resources :ratings
end
root 'schools#index'
end
The error is undefined method 'team_id' for Player:0x007fb5f41f3838.
I am trying to edit players and I am not able to do that because of an undefined method.
My guess is it has something to do with my relations. I am learning relations between models so they may not be correct.
This is my Player Model
class Player < ActiveRecord::Base
validates_length_of :description, :maximum=>4000
has_many :descriptions, through: :fouls
has_many :fouls, as: :foul_by_id
has_many :fouls, as: :foul_on_id
belongs_to :team
end
This is my Player Controller
class PlayersController < ApplicationController
before_action :authenticate_user!
before_action :most_recent_fouls
def index
#players = Player.all
end
def show
#player = Player.find(params[:id])
end
def new
#player = Player.new
end
def create
#player = Player.new(players_params)
if #player.save
redirect_to(:action => "index")
else
render("new")
end
end
def edit
#player = Player.find(params[:id])
end
def update
#player = Player.find(params[:id])
if #player.update_attributes(players_params)
redirect_to(:action => "show", :id => #player.id)
else
render("index")
end
end
def destroy
player = Player.find(params[:id]).destroy
redirect_to(:action => "index")
end
private
def players_params
params.require(:player).permit(:name, :number, :position, :bios, :descriptions, :team_id)
end
end
Because of my gut saying that it has to do with relations, here is my Team Model
class Team < ActiveRecord::Base
has_many :players
validates :name, presence: true
end
My migration table for Player
class CreatePlayers < ActiveRecord::Migration
def change
create_table :players do |p|
p.string :name
p.string :number
p.string :position
p.string :bio
p.string :description
p.integer :team_id
p.timestamps
end
end
end
Any help is appreciated. Please explain your answer. Tell me if you need any more code to be displayed.
/config/routes.rb
Rails.application.routes.draw do
devise_for :users
root 'posts#hello'
resources :users
resources :posts
end
/app/controllers/posts_controller.rb
class PostsController < ApplicationController
before_filter :authenticate_user! , except: [:hello]
def hello
end
def new
end
def create
#post = Post.create(inner)
redirect_to post_path(#post.id)
end
def index
#posts = Post.all.order('id desc')
end
def show
#post = Post.find_by(id: params[:id])
end
private
def inner
params.require(:post).permit(:title, :desc)
end
end
When I click posts_path link, I get an error: uninitialized constant PostsController::Post app/controllers/posts_controller.rb, line 17
def index
#posts = Post.all.order('id desc')
end
Whats wrong?
UPD
class Post < ActiveRecord::Base
belongs_to :user
validates :desc, presence: true
validates :title, presence: true, length: { maximum: 45 }
end
UPD2
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.string :title
t.string :desc
t.timestamps
end
end
end
As per Rails convention model names should be singular. So, model Post would be located under folder app/models and named post.rb and NOT Posts.rb. You are getting the error because Rails would look for a file named post.rb by convention and if not found it throws the error.