Ruby Error PagesController#main - ruby-on-rails

Site link xxx.com/ru does not work
Error log:
Processing by PagesController#main as HTML
Parameters: {"locale"=>"ru"}
Rendered pages/main.html.erb within layouts/application (27.7ms)
Completed 500 Internal Server Error in 46ms
ActionView::Template::Error (undefined method `title' for nil:NilClass):
19:
20: <article class="hello">
21: <dl>
22: <dt><%= #page.title %></dt>
23: <dd><%=raw nl2br #page.content.html_safe %></dd>
24: </dl>
25: </article>
app/views/pages/main.html.erb:22:in `_app_views_pages_main_html_erb___1446230423625798988_17243439220'
If you go on the link "xxx.com/ru/pages#main", then it works
UPD: Now only works /ru, /en - does not work
Error:
Processing by PagesController#main as HTML
Parameters: {"locale"=>"en"}
Completed 404 Not Found in 1ms
ActiveRecord::RecordNotFound (Couldn't find Page with id=2):
app/controllers/pages_controller.rb:11:in `main'
What could be the problem? I beg you to help solve it, the site should be opened soon, and he is not all work, one programmer messed up code.
Controller file:
class PagesController < ApplicationController
before_filter :authenticate, :only => [:index, :show, :new, :edit, :create, :update, :destroy ]
caches_page :main, :about, :showreal, :projects, :contacts, :reject
caches_action :index, :show, :new
def main
#page = case I18n.locale.to_s
when 'ru'; Page.where("id =?", 4).first
when 'zh'; Page.where("id =?", 6).first
else Page.where("id =?", 6).first
end
base = 'app/assets/videos/'
#video = Dir.glob(File.join(base, 'main', 'video.*')).first.sub!(base,"")
#preview = Dir.glob(File.join(base, 'main', 'preview.*')).first.sub!(base,"")
end
def about
#body_class = 'leftbg'
#page = case I18n.locale.to_s
when 'ru'; Page.find(3)
when 'zh'; Page.find(5)
else Page.find(1)
end
end
def showreal
base = 'app/assets/videos/'
#video = Dir.glob(File.join(base, 'showreal', 'video.*')).first.sub!(base,"")
#preview = Dir.glob(File.join(base, 'showreal', 'preview.*')).first.sub!(base,"")
end
def projects
end
def contacts
#body_class = 'leftbg'
end
def sent
redirect_to :action => "reject" and return unless request.post?
#body_class = 'leftbg'
if request.POST.include? 'name'
#name = request.params['name']
end
if request.POST.include? 'email'
#email = request.params['email']
end
if request.POST.include? 'phone'
#phone = request.params['phone']
end
if request.POST.include? 'message'
#message = request.params['message']
end
if ['name','email','phone','message'].all? {|i| request.POST.include?(i)}
ContactMailer.contacts_email(#name,#email,#phone,#message).deliver
else
flash[:error] = 'You must complete all fields!'
return render :action => "contacts"
end
end
def reject
#body_class = 'leftbg'
end
# GET /pages
# GET /pages.json
def index
#pages = Page.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #pages }
end
end
# GET /pages/1
# GET /pages/1.json
def show
#page = Page.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #page }
end
end
# GET /pages/new
# GET /pages/new.json
def new
#page = Page.new
expire_page :action => [:main, :about]
expire_action :action => [:index, :show]
respond_to do |format|
format.html # new.html.erb
format.json { render json: #page }
end
end
# GET /pages/1/edit
def edit
#page = Page.find(params[:id])
end
# POST /pages
# POST /pages.json
def create
#page = Page.new(params[:page])
respond_to do |format|
if #page.save
format.html { redirect_to #page, notice: 'Page was successfully created.' }
format.json { render json: #page, status: :created, location: #page }
else
format.html { render action: "new" }
format.json { render json: #page.errors, status: :unprocessable_entity }
end
end
end
# PUT /pages/1
# PUT /pages/1.json
def update
#page = Page.find(params[:id])
expire_page :action => [:main, :about]
expire_action :action => [:index, :show]
respond_to do |format|
if #page.update_attributes(params[:page])
format.html { redirect_to #page, notice: 'Page was successfully updated.' }
format.json { head :ok }
else
format.html { render action: "edit" }
format.json { render json: #page.errors, status: :unprocessable_entity }
end
end
end
# DELETE /pages/1
# DELETE /pages/1.json
def destroy
#page = Page.find(params[:id])
#page.destroy
expire_page :action => [:main, :about]
expire_action :action => [:index, :show]
respond_to do |format|
format.html { redirect_to pages_url }
format.json { head :ok }
end
end
end

I believe #page is nil, so please try:
<%= #page.try(:title) %>
or:
<dt><%= #page.title if #page.present?%></dt>
<dt><%= raw nl2br #page.content.html_safe if #page.content.present? if #page.present? %></dt>
or, in the controller's action, you can write it like:
if #page.blank?
flash[:error] = 'Page not found.'
redirect_to root_path
end
As per the controller code, Please modify the case block.
def main
##page = case I18n.locale.to_s
# when 'ru'; Page.where("id =?", 4).first
# when 'zh'; Page.where("id =?", 6).first
# else Page.where("id =?", 6).first
#end
page_id = (I18n.locale.to_s == 'ru') ? 4 : 6
#page = Page.where(id: page_id).first
base = 'app/assets/videos/'
#video = Dir.glob(File.join(base, 'main', 'video.*')).first.sub!(base,"")
#preview = Dir.glob(File.join(base, 'main', 'preview.*')).first.sub!(base,"")
end

Related

Ruby on Rails throws error when removing items from a cart

I have 3 models: Cart, LineItems and Tracks
I add tracks to my cart via associations with line_items.
I can successfully add a track to a cart, but when I go to remove it the following error is thrown:
undefined method 'line_items' for nil:NilClass
Which is weird considering the method that throws the error doesn't raise the same error when an item gets added; any idea what gives?
The application maintains a cart attached to a user's session and uses the session id to recognise a unique cart.
helpers > application_helper.rb
module ApplicationHelper
def cart_count_over_one
if cart_has_items
return "<span class='tag is-dark'>#{cart_has_items}</span>".html_safe
end
end
def cart_has_items
total = #cart.line_items.map{ |item| item.quantity }.sum #error occurs here
return total if total > 0
end
end
views > layouts> application.html.haml
!!!
%html
%head
%title Home
%meta{:content => "width=device-width, initial-scale=1", :name => "viewport"}/
= stylesheet_link_tag 'https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css'
= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload'
= javascript_include_tag 'modernizr'
= csrf_meta_tags
%body{:class => yield(:body_class)}
- if flash[:notice]
.notification.is-success.global-notification
%p.notice= notice
- if flash[:alert]
.notification.is-danger.global-notification
%p.alert= alert
%nav.navbar.is-warning{"aria-label" => "main navigation", :role => "navigation"}
.navbar-brand
= link_to root_path, class:"navbar-item" do
%h1.title.is-centered Cscades
.navbar-burger.burger{"data-target" => "navbar"}
%span
%span
%span
#navbar.navbar-menu
.navbar-end
.navbar-item
.field.is-grouped
- if cart_has_items #method gets called here
= link_to cart_path(#cart), class:"navbar-item button is-warning" do
%span.icon.is-small
%i.fa.fa-shopping-cart
%span
Cart
\#{cart_count_over_one}
- if user_signed_in?
= link_to 'Sell', new_track_path, class: "navbar-item button is-dark"
.navbar-item.has-dropdown.is-hoverable
= link_to 'Account', edit_user_registration_path, class: "navbar-link"
.navbar-dropdown.is-right
= link_to current_user.name, edit_user_registration_path, class:"navbar-item"
= link_to "Log Out", destroy_user_session_path, method: :delete, class:"navbar-item"
- else
= link_to "Sign In", new_user_session_path, class:"navbar-item button is-warning"
= link_to "Sign up", new_user_registration_path, class:"navbar-item button is-warning"
= yield(:header)
.container
= yield
line_items_controller.rb
class LineItemsController < ApplicationController
include CurrentCart
before_action :set_cart, only: [:create]
before_action :set_line_item, only: [:show, :edit, :update, :destroy]
# GET /line_items
# GET /line_items.json
def index
#line_items = LineItem.all
end
# GET /line_items/1
# GET /line_items/1.json
def show
end
# GET /line_items/new
def new
#line_item = LineItem.new
end
# GET /line_items/1/edit
def edit
end
# POST /line_items
# POST /line_items.json
def create
#track = Track.find(params[:track_id])
#line_item = #cart.add_track(#track)
respond_to do |format|
if #line_item.save
format.html { redirect_to #line_item, notice: 'Line item was successfully created.' }
format.json { render :show, status: :created, location: #line_item }
else
format.html { render :new }
format.json { render json: #line_item.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /line_items/1
# PATCH/PUT /line_items/1.json
def update
respond_to do |format|
if #line_item.update(line_item_params)
format.html { redirect_to #line_item, notice: 'Line item was successfully updated.' }
format.json { render :show, status: :ok, location: #line_item }
else
format.html { render :edit }
format.json { render json: #line_item.errors, status: :unprocessable_entity }
end
end
end
# DELETE /line_items/1
# DELETE /line_items/1.json
def destroy
#cart = Cart.find(session[:cart_id])
#line_item.destroy
respond_to do |format|
format.html { redirect_to cart_path(#cart), notice: 'Line item was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_line_item
#line_item = LineItem.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def line_item_params
params.require(:line_item).permit(:track_id)
end
end
carts_controller.rb
class CartsController < ApplicationController
rescue_from ActiveRecord::RecordNotFound, with: :invalid_cart
before_action :set_cart, only: [:show, :edit, :update, :destroy]
# GET /carts
# GET /carts.json
def index
#carts = Cart.all
end
# GET /carts/1
# GET /carts/1.json
def show
end
# GET /carts/new
def new
#cart = Cart.new
end
# GET /carts/1/edit
def edit
end
# POST /carts
# POST /carts.json
def create
#cart = Cart.new(cart_params)
respond_to do |format|
if #cart.save
format.html { redirect_to #cart, notice: 'Cart was successfully created.' }
format.json { render :show, status: :created, location: #cart }
else
format.html { render :new }
format.json { render json: #cart.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /carts/1
# PATCH/PUT /carts/1.json
def update
respond_to do |format|
if #cart.update(cart_params)
format.html { redirect_to #cart, notice: 'Cart was successfully updated.' }
format.json { render :show, status: :ok, location: #cart }
else
format.html { render :edit }
format.json { render json: #cart.errors, status: :unprocessable_entity }
end
end
end
# DELETE /carts/1
# DELETE /carts/1.json
def destroy
#cart.destroy if cart.id == session[:cart_id] #hook into current client session instead of user
session[:cart_id] = nil
respond_to do |format|
format.html { redirect_to root-path, notice: 'Cart was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_cart
#cart = Cart.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def cart_params
params.fetch(:cart, {})
end
def invalid_cart
logger.error "Attempt to access invalid cart #{params[:id]}"
redirect_to root_path, notice: "That cart doesn't exist"
end
end
The error message says:
undefined method 'line_items' for nil:NilClass
Which as you say points to:
def cart_has_items
total = #cart.line_items.map{ |item| item.quantity }.sum #error occurs here
return total if total > 0
end
You're trying to call line_items on #cart, which in this case is apparently nil.
Try putting a check in before, changing it to something like:
def cart_has_items
return false unless #cart
total = #cart.line_items.map{ |item| item.quantity }.sum #error occurs here
return total if total > 0
end

Link to Order Index Rails 4

I am using Rails 4 with the Impressionist gem to get view count of my Articles.
On my index page I have a link labeled "Most Popular"
I also have access to a method that will order articles by the view count:
#articles = Article.order('impressions_count ASC')
What is the best way to order the index by impression_count when a user clicks the "most popular button?" I am having trouble finding documentation on this.
Here is my articles_controller.rb
class ArticlesController < ApplicationController
load_and_authorize_resource
before_action :set_article, only: [:show, :edit, :update, :destroy]
def index
if params[:q].present?
#articles = Article.search(params[:q], misspellings: {edit_distance: 1}, page: params[:page], per_page: 12)
#search = current_or_guest_user.searches.create!(query: params[:q], searched_at: Time.now)
else
#articles = Article.order('impressions_count ASC').page(params[:page]).per(12)
#search = current_or_guest_user.searches.create!(query: params[:q], searched_at: Time.now)
end
if #articles.blank?
return redirect_to request_path
#search = current_or_guest_user.searches.create!(query: params[:q], searched_at: Time.now)
end
get_query
end
def autocomplete
#articles = Article.search params[:term], autocomplete: true
render json: #articles
end
def search
#articles = Article.search params[:q], suggest: true, page: params[:page], per_page: 5
#search = current_or_guest_user.searches.create!(query: params[:q], searched_at: Time.now)
render 'index'
end
def show
impressionist(#article, nil, { unique: [:session_hash] })
#skip_error = true
#subarticles = #article.subarticles.approved.order(:cached_votes_score => :desc)
if request.path != article_path(#article)
redirect_to #article, status: :moved_permanently
else
respond_to do |format|
format.html # show.html.erb
format.json { render json: #article }
end
end
end
def new
end
def edit
end
def create
respond_to do |format|
if #article.save
format.html { redirect_to #article, notice: 'Article was successfully created.' }
format.json { render :show, status: :created, location: #article }
else
format.html { render :new }
format.json { render json: #article.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #article.update(article_params)
format.html { redirect_to #article, notice: 'Article was successfully updated.' }
format.json { render :show, status: :ok, location: #article }
else
format.html { render :edit }
format.json { render json: #article.errors, status: :unprocessable_entity }
end
end
end
def destroy
#article.destroy
respond_to do |format|
format.html { redirect_to articles_url, notice: 'Article was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_article
#article = Article.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def article_params
params.require(:article).permit(:title, :specific, :category, :aka, :image1, :image2, :video1, :video2)
end
def get_query
#userquery = params[:q]
end
end
The first else clause in your index is this:
else
#articles = Article.order('impressions_count ASC').page(params[:page]).per(12)
That is why you are getting them sorted by impressions_count. Just get rid of it to return them sorted by most recent.
else
#articles = Article.order(created_at: :desc).page(params[:page]).per(12)
You then need to set your "most popular" link to return the #articles variable sorted by impressions_count as you did in your old code.
You will need to make your action in the controller to return the results you want, something like:
Add a variable to your whitelist:
def article_params
params.require(:article).permit(:title, :specific, :category, :aka, :image1, :image2, :video1, :video2, :imp_sort)
end
Then in your index action you can add it in:
def index
if params[:q].present?
#articles = Article.search(params[:q], misspellings: {edit_distance: 1}, page: params[:page], per_page: 12)
#search = current_or_guest_user.searches.create!(query: params[:q], searched_at: Time.now)
else
if article_params[:imp_sort]
#articles = Article.order('impressions_count ASC').page(params[:page]).per(12)
else
#articles = Article.order(created_at: :desc).page(params[:page]).per(12)
end
#search = current_or_guest_user.searches.create!(query: params[:q], searched_at: Time.now)
end
if #articles.blank?
return redirect_to request_path
#search = current_or_guest_user.searches.create!(query: params[:q], searched_at: Time.now)
end
get_query
end
in your index.html.erb you will need to have your link do something like:
<%= link_to "Sort by Impressions", articles_path(:imp_sort => true) %>

Forbidden Attribute Error params ruby search form

I am having an isuue. I am creating a search form in my form. The form has restaurant name, city, and state.
Looks like this:
<%= form_tag(restaurants_path, :method => "get", id: "search-form") do %>
<%= label_tag(:restaurant_name) %>
<%= text_field_tag :restaurant_name, params[:restaurant_name] %> <br />
<%= label_tag(:city, "Restaurant City") %>
<%= text_field_tag :city, params[:city] %> <br />
<%= label_tag(:state, "Restaurant State") %>
<%= text_field_tag :state, params[:state] %> <br />
<%= submit_tag "Search", :name => nil %>
<% end %>
Now I am trying to get information for a part restaurant name/location.
I have seen that if my form is coded properly, which it is you can do something like:
Restaurant Controller:
class RestaurantsController < ApplicationController
before_action :set_restaurant, only: [:show, :edit, :update, :destroy, :search]
# GET /restaurants
# GET /restaurants.json
def index
constraints = Hash.new
constraints[:restaurant_name] = params[:restaurant_name]
constraints[:city] = params[:city]
if params[:restaurant_name] && params[:city]
##restaurants = Restaurant.search(params[:restaurant_name]).order('restaurant_name desc').paginate(:per_page => 5, :page => params[:page])
#restaurants = Restaurant.where(params).order('restaurant_name desc').paginate(:per_page => 5, :page => params[:page])
else
#restaurants = Restaurant.order('restaurant_name desc').paginate(:per_page => 5, :page => params[:page])
end
end
# GET /restaurants/1
# GET /restaurants/1.json
def show
end
# GET /restaurants/new
def new
#restaurant = Restaurant.new
end
# GET /restaurants/1/edit
def edit
end
# POST /restaurants
# POST /restaurants.json
def create
#restaurant = Restaurant.new(restaurant_params)
respond_to do |format|
if #restaurant.save!
session[:page] = 0
format.html { redirect_to restaurants_url, notice: 'Restaurant was successfully created.' }
format.json { head :no_content }
else
format.html { render :new }
format.json { render json: #restaurant.errors, status: :unprocessable_entity }
end
end
end
# GET /restaurants/1/search
# GET /restaurants/1.json
def gotosearch
end
def self.search
Restaurant.where("restaurant_name like ? AND city like ? ", params[:restaurant_name], params[:city])
end
# PATCH/PUT /restaurants/1
# PATCH/PUT /restaurants/1.json
def update
respond_to do |format|
if #restaurant.update(restaurant_params)
format.html { redirect_to #restaurant, notice: 'Restaurant was successfully updated.' }
format.json { render :show, status: :ok, location: #restaurant }
else
format.html { render :edit }
format.json { render json: #restaurant.errors, status: :unprocessable_entity }
end
end
end
# DELETE /restaurants/1
# DELETE /restaurants/1.json
def destroy
#restaurant.destroy
respond_to do |format|
format.html { redirect_to restaurants_url, notice: 'Restaurant was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_restaurant
#restaurant = Restaurant.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def restaurant_params
params.require(:restaurant).permit(:restaurant_name, :street, :city, :state, :zip, :split_the_check, :dont_split_the_check)
end
end
The problem is on this line:
#restaurants = Restaurant.where(params).order('restaurant_name desc').paginate(:per_page => 5, :page => params[:page])
You are searching with a variable called params, which holds all the parameters for the request. You need to do something more specific like this:
#restaurants = Restaurant.where(params[:restaurant_name]).order('restaurant_name desc').paginate(:per_page => 5, :page => params[:page])
Or you can search by constraints[:restaurant_name] since you're already declaring that variable.
And if you're searching based on multiple attributes you can do this:
#restaurants = Restautanr.where("restaurant_name = ? OR name = ? OR state = ?", params[:restaurant_name], params[:city], params[:state])

Ruby Error ActiveRecord::RecordNotFound

The page you were looking for doesn't exist. You may have mistyped the address or the page may have moved.
Error log:
Started GET "/ru" for 0.0.0.0 at 2014-04-08 08:03:02 +0300
Processing by PagesController#main as HTML
Parameters: {"locale"=>"ru"}
Completed 404 Not Found in 14ms
ActiveRecord::RecordNotFound (Couldn't find Page with id=4):
app/controllers/pages_controller.rb:9:in `main'
pages_controller:
class PagesController < ApplicationController
before_filter :authenticate, :only => [:index, :show, :new, :edit, :create, :update, :destroy ]
caches_page :main, :about, :showreal, :projects, :contacts, :reject
caches_action :index, :show, :new
def main
#page = case I18n.locale.to_s
when 'ru'; Page.find(4)
when 'zh'; Page.find(6)
else Page.find(2)
end
base = 'app/assets/videos/'
#video = Dir.glob(File.join(base, 'main', 'video.*')).first.sub!(base,"")
#preview = Dir.glob(File.join(base, 'main', 'preview.*')).first.sub!(base,"")
end
def about
#body_class = 'leftbg'
#page = case I18n.locale.to_s
when 'ru'; Page.find(3)
when 'zh'; Page.find(5)
else Page.find(1)
end
end
def showreal
base = 'app/assets/videos/'
#video = Dir.glob(File.join(base, 'showreal', 'video.*')).first.sub!(base,"")
#preview = Dir.glob(File.join(base, 'showreal', 'preview.*')).first.sub!(base,"")
end
def projects
end
def contacts
#body_class = 'leftbg'
end
def sent
redirect_to :action => "reject" and return unless request.post?
#body_class = 'leftbg'
if request.POST.include? 'name'
#name = request.params['name']
end
if request.POST.include? 'email'
#email = request.params['email']
end
if request.POST.include? 'phone'
#phone = request.params['phone']
end
if request.POST.include? 'message'
#message = request.params['message']
end
if ['name','email','phone','message'].all? {|i| request.POST.include?(i)}
ContactMailer.contacts_email(#name,#email,#phone,#message).deliver
else
flash[:error] = 'You must complete all fields!'
return render :action => "contacts"
end
end
def reject
#body_class = 'leftbg'
end
# GET /pages
# GET /pages.json
def index
#pages = Page.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #pages }
end
end
# GET /pages/1
# GET /pages/1.json
def show
#page = Page.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #page }
end
end
# GET /pages/new
# GET /pages/new.json
def new
#page = Page.new
expire_page :action => [:main, :about]
expire_action :action => [:index, :show]
respond_to do |format|
format.html # new.html.erb
format.json { render json: #page }
end
end
# GET /pages/1/edit
def edit
#page = Page.find(params[:id])
end
# POST /pages
# POST /pages.json
def create
#page = Page.new(params[:page])
respond_to do |format|
if #page.save
format.html { redirect_to #page, notice: 'Page was successfully created.' }
format.json { render json: #page, status: :created, location: #page }
else
format.html { render action: "new" }
format.json { render json: #page.errors, status: :unprocessable_entity }
end
end
end
# PUT /pages/1
# PUT /pages/1.json
def update
#page = Page.find(params[:id])
expire_page :action => [:main, :about]
expire_action :action => [:index, :show]
respond_to do |format|
if #page.update_attributes(params[:page])
format.html { redirect_to #page, notice: 'Page was successfully updated.' }
format.json { head :ok }
else
format.html { render action: "edit" }
format.json { render json: #page.errors, status: :unprocessable_entity }
end
end
end
# DELETE /pages/1
# DELETE /pages/1.json
def destroy
#page = Page.find(params[:id])
#page.destroy
expire_page :action => [:main, :about]
expire_action :action => [:index, :show]
respond_to do |format|
format.html { redirect_to pages_url }
format.json { head :ok }
end
end
end
What could be the problem?
Stopped all work after work of a programmer, he was doing something with the cache.
Problem is here
#page = Page.find(2)
Instead of using find, use where
#page = Page.where("id =?", 2).first
Then you can apply a check like
if #page.blank?
#do something
else
#do something else
end
Here's the update
#page = case I18n.locale.to_s
when 'ru'; Page.where("id =?", 4).first
when 'zh'; Page.where("id =?", 6).first
else Page.where("id =?", 6).first
end

New action not working, routing error when calling Category.new()

I had a custom reorder action working where it created new items through ajax.
After making some changes to other parts of the site the New action doesn't work.
When I go to the page categories/reorder, or categories/new it loads the page properly, but only if I comment out the line #category = Category.new().
As soon as I try to set #category = Category.new(), #category = Category.new(:parent_id => params[:parent_id]), or #category = Category.new it gives me the error message:
No route matches {:action=>"edit", :controller=>"categories", :id=>#<Category _id: 515ee18c10188f64fb000001, created_at: nil, updated_at: nil, deleted_at: nil, ancestry: nil, user_id: nil, name: nil, description: nil, image: nil, lock: nil, _slugs: []>}
I dropped my database in case there was some entry that somehow gave me this error, but on logging in again it still gives me this message.
Here's my routes file:
match '/auth/:provider/callback' => 'sessions#create'
match '/auth/failure' => 'sessions#failure'
match '/signout' => 'sessions#destroy', :as => :signout
match '/signin' => 'sessions#new', :as => :signin
match "reorder/symbols" => "categories#reorder", :via => :get, :as => :reorder_symbols
resources :pages do
resources :blocks do
collection { post :sort }
end
end
get 'symbols/:id/search/', to: 'categories#search', as: :sift_meanings
get "logout" => "sessions#destroy", :as => "logout"
get "login" => "sessions#new", :as => "login"
get "signup" => "users#new", :as => "signup"
resources :users
resources :sessions
match "meanings/:id/delete" => "meanings#destroy", :via => :get, as: :delete_meaning
match "symbols/gallery/:id" => "categories#gallery", :via => :get
resources :symbols, :as => :categories, :controller => :categories do
resources :meanings
collection {post :sort}
end
root :to => 'categories#index'
Controller file:
class CategoriesController < ApplicationController
helper :lego
helper :meanings
def index
#categories = Category.all
if params[:id]
#categories = Category.find(params[:id]) #if params[:id]
#categories = #categories.subtree.arrange(:order => 'name')
elsif params[:view] == "alpha"
#alphabet = Category.all.group_by{|c| c.name[0]}
#see_kids = false
#categories = #categories.sort(:name => "ASC") if !params[:letter]
#categories = #categories.where(name: eval("/^#{params[:letter]}/i")).sort(:name => "ASC") if params[:letter]
else
# #categories = Category.all
#categories = #categories.arrange(:order => 'name') #if params[:view] != "list"
end
respond_to do |format|
format.html # index.html.erb
format.js
format.json { render json: #categories }
end
end
def reorder
if Rails.env != "production" && !request.xhr?
flash[:info] = "Currently in #{Rails.env} mode."
end
#categories = Category.arrange(:order => 'name')
# #category = Category.new
#next = Category.count
respond_to do |format|
format.html # index.html.erb
format.js
format.json { render json: #categories }
end
end
def sort
params[:category].each do |id, attr|
thisCat = params[:category][id]
#category = Category.where(:_id => id).first
if thisCat.nil? || thisCat == 'null'
#category.parent_id = nil
else
#category.parent_id = thisCat.to_s
end
#category.save
end
end
def gallery
#categories = Category.arrange(:order => 'name')
#category = Category.find(params[:id])
#siblings = Category.siblings_of(params[:id])
respond_to do |format|
format.html # index.html.erb
format.js
format.json { render json: #category }
end
end
def show
#categories = Category.arrange(:order => 'name')
#category = Category.find(params[:id])
#updater = User.find(#category.user) || nil
#siblings = Category.siblings_of(params[:id])
#meanings = #category.meanings #Meaning.where(:category_id => params[:id])
#belief_list = []
#culture_list = []
#contributors = []
#connotations = []
for meaning in #meanings
for belief in meaning.beliefs
#belief_list << belief
end
for culture in meaning.cultures
#culture_list << culture
end
#connotations << meaning.connotation
#contributors << meaning.user
end
#beliefs = #belief_list.uniq
#cultures = #culture_list.uniq
#contributors = #contributors.uniq
#connotations = #connotations.uniq
respond_to do |format|
format.html # show.html.erb
format.js
format.json { render json: #category }
end
end
def search
#categories = Category.arrange(:order => 'name')
#category = Category.find(params[:id])
#meanings = #category.meanings
#meanings = #meanings.where(:beliefs => params[:beliefs]) if params[:beliefs]
#meanings = #meanings.where(:cultures => params[:cultures]) if params[:cultures]
#meanings = #meanings.where(:connotation => params[:connotation]) if params[:connotation]
#meanings = #meanings.where(:user => params[:user]) if params[:user]
end
# GET /categories/new
# GET /categories/new.json
def new
#category = Category.new(:parent_id => params[:parent_id])
# #category.photo.build
respond_to do |format|
format.html # new.html.erb
format.js
format.json { render json: #category }
end
end
# GET /categories/1/edit
def edit
#category = Category.find(params[:id])
end
# POST /categories
# POST /categories.json
def create
#category = Category.new(params[:category])
#category.user = current_user
#categories = Category.arrange(:order => :created_at)
if #category.save
flash[:success] = "<h4><i class=icon-ok></i> '#{#category.name}' was successfully created.</h4>"
end
respond_to do |format|
if #category.save
format.html { redirect_to #categories, notice: 'Category was successfully created.' }
format.js
format.json { render json: #categories, status: :created, location: #category }
else
format.html { render action: "new" }
format.js
format.json { render json: #category.errors, status: :unprocessable_entity }
end
end
end
# PUT /categories/1
# PUT /categories/1.json
def update
#category = Category.find(params[:id])
#category.user = current_user
flash[:success] = "<h4><i class=icon-ok></i> #{#category.name} was successfully updated.</h4>"
respond_to do |format|
if #category.update_attributes(params[:category])
format.html { redirect_to #category}
format.js
format.json { head :no_content }
else
format.html { render action: "edit", error: "Unable to update '#{#category.name}'", status: :unprocessable_entity }
format.json { render json: #category.errors, status: :unprocessable_entity }
end
end
end
# DELETE /categories/1
# DELETE /categories/1.json
def destroy
#category = Category.find(params[:id])
#category.destroy
flash[:alert] = "<h4><i class=icon-warning-sign></i> Warning. You have deleted the category '#{#category.name}'.</h4>".html_safe
respond_to do |format|
format.html { redirect_to categories_url }
format.json { head :no_content }
format.js
end
end
def has_sidebar?
self.has_children?
end
private
end
The only other thing to note, I found that on reverting to an older working version I have to restart the server because of a less Twitter Bootstrap variable not being set right. But I don't think that should be affecting this.
If you follow the stack trace, it will show you where the error is. Since you mentioned that this only happens when you add a call to #category = Category.new, I can only think that this is because you are using #category to create an edit link. But since #category is a new object, you'll get errors. Try to look at the view files where edit links can be found.

Resources