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
Related
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
My issue is, when I am under the camper show page
Current Camper URL:
campers/1
and I go to click on to view the appointment it uses the camper_id for the appointment_id which is wrong so say if the camper_id is 1 it will use the appointment_id as 1 and actually the appointment id is 3, so then it says Couldn't find appointment with id of 1.
Table Header
<% #appointments.each do |app| %>
<%= link_to app.camper.camperName, appointment_path(#camper, #appointment) %>
Campers Controller Show Action
#appointments = #camper.appointments
Camper Model
has_many :appointments, dependent: :destroy
Appointment Model
belongs_to :camper
Shallow Nested Routes File
resources :customers, shallow: :true do
resources :campers do
resources :appointments do
resources :orders do
member do
patch :complete
end
end
end
end
end
Camper Controller
class CampersController < ApplicationController
before_action :set_camper, only: [:show, :edit, :update, :destroy]
# before_action :set_customer, only: [:index, :new, :edit, :create, :update]
load_and_authorize_resource
# GET /campers
# GET /campers.json
def index
#campers = #customer.campers
end
def list
query = params[:q].presence || ""
#campers = Camper.search(query, page: params[:page], per_page: 20, order: {created_at: :desc} )
end
# GET /campers/1
# GET /campers/1.js
def show
#appointments = #camper.appointments
respond_to do |format|
format.html
format.json
end
end
# GET /campers/new
def new
#customer = Customer.find(params[:customer_id])
#camper = #customer.campers.build
end
# GET /campers/1/edit
def edit
end
def page_name
"Campers"
end
# POST /campers
# POST /campers.json
def create
#camper = Camper.new(camper_params)
respond_to do |format|
if #camper.save
format.html { redirect_to camper_path(#camper), notice: 'Camper was successfully created.' }
format.json { render :show, status: :created, location: #camper }
else
format.html { render :new }
format.json { render json: #camper.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /campers/1
# PATCH/PUT /campers/1.json
def update
respond_to do |format|
if #camper.update(camper_params)
format.html { redirect_to camper_path(#camper), notice: 'Camper was successfully updated.' }
format.json { render :show, status: :ok, location: #camper }
else
format.html { render :edit }
format.json { render json: #camper.errors, status: :unprocessable_entity }
end
end
end
# DELETE /campers/1
# DELETE /campers/1.json
def destroy
#camper.destroy
respond_to do |format|
format.html { redirect_to root_path, notice: 'Camper was successfully deleted.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_camper
#camper = Camper.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def camper_params
params.require(:camper).permit(:order_id, :customer_id, :year, :manufacturer, :modelName, :camperClass, :vin, :mileage, :notes, :user_id)
end
end
Appointments Controller
class AppointmentsController < ApplicationController
before_action :set_appointment, only: [:show, :edit, :update, :destroy]
# GET /appointments
# GET /appointments.json
def index
#camper = Camper.find(params[:camper_id])
#appointments = #camper.appointments
end
# GET /appointments/1
# GET /appointments/1.json
def show
#orders = #appointment.orders
end
# GET /appointments/newå
def new
#camper = Camper.find(params[:camper_id])
#appointment = #camper.appointments.build
end
# GET /appointments/1/edit
def edit
end
# POST /appointments
# POST /appointments.json
def create
#appointment = Appointment.new(appointment_params)
respond_to do |format|
if #appointment.save
format.html { redirect_to appointment_path(#appointment), notice: 'Appointment was successfully created.' }
format.json { render :show, status: :created, location: #appointment }
else
format.html { render :new }
format.json { render json: #appointment.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /appointments/1
# PATCH/PUT /appointments/1.json
def update
respond_to do |format|
if #appointment.update(appointment_params)
format.html { redirect_to #appointment, notice: 'Appointment was successfully updated.' }
format.json { render :show, status: :ok, location: #appointment }
else
format.html { render :edit }
format.json { render json: #appointment.errors, status: :unprocessable_entity }
end
end
end
# DELETE /appointments/1
# DELETE /appointments/1.json
def destroy
#appointment.destroy
respond_to do |format|
format.html { redirect_to camper_appointments_path(#appointment), notice: 'Appointment was successfully deleted.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_appointment
#appointment = Appointment.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def appointment_params
params.require(:appointment).permit(:customer_id, :camper_id, :order_id, :title, :description, :date_in, :date_out)
end
end
appointment_path only takes a single appointment argument. Remove the #camper argument:
appointment_path(#appointment)
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
I've created an activity model and I'm trying to have it so that when a user deletes their activity it also deletes the corresponding status. I've been able to do it when deleting the status, it deletes the activity but not sure how to do it in the opposite direction. I tried finding the status by targetable_id but I get:
undefined method `find_by_targetable_id' for #<Class:0x8df4a70>
Parameters:
{"_method"=>"delete",
"authenticity_token"=>"s2wKOZxCBVarT5uge3AIFNXHepFuvNGM+kU/q+ArOjA=",
"id"=>"18"}
If you're familiar with the public_activity gem then targetable is the same thing as trackable and in this example, the activity id is 18 and it's corresponding status id is 53
ActivitiesController
class ActivitiesController < ApplicationController
before_filter :authenticate_member!, only: [:destroy]
before_filter :find_activity, only: [:destroy]
def index
following_ids = current_member.following_members.map(&:id)
#activities = Activity.where("member_id in (?)", following_ids.push(current_member.id)).order("created_at desc").all
end
def destroy
#status = Activity.targetable
if #status
#status.destroy
end
#activity.destroy
respond_to do |format|
format.html { redirect_to :back }
format.json { head :no_content }
end
end
private
def find_activity
#activity = current_member.activities.find(params[:id])
end
end
StatusesController
class StatusesController < ApplicationController
before_filter :authenticate_member!, only: [:new, :create, :edit, :update, :destroy]
before_filter :find_member
before_filter :find_status, only: [:edit, :update, :destroy, :show]
rescue_from ActiveRecord::RecordNotFound do
render file: 'public/404', status: 404, formats: [:html]
end
# GET /statuses
# GET /statuses.json
def index
#statuses = Status.order('created_at desc').all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #statuses }
end
end
# GET /statuses/1
# GET /statuses/1.json
def show
respond_to do |format|
format.html # show.html.erb
format.json { redirect_to profile_path(current_member) }
end
end
# GET /statuses/new
# GET /statuses/new.json
def new
#status = Status.new
#status.build_document
respond_to do |format|
format.html # new.html.erb
format.json { render json: #status }
end
end
# GET /statuses/1/edit
def edit
end
# POST /statuses
# POST /statuses.json
def create
#status = current_member.statuses.new(params[:status])
respond_to do |format|
if #status.save
current_member.create_activity(#status, 'created')
format.html { redirect_to :back }
format.json
else
format.html { redirect_to profile_path(current_member), alert: 'Post wasn\'t created. Please try again and ensure image attchments are under 10Mbs.' }
format.json { render json: #status.errors, status: :unprocessable_entity }
end
end
end
# PUT /statuses/1
# PUT /statuses/1.json
def update
if params[:status] && params[:status].has_key?(:user_id)
params[:status].delete(:user_id)
end
respond_to do |format|
if #status.update_attributes(params[:status])
format.html { redirect_to profile_path(current_member), notice: 'Status was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #status.errors, status: :unprocessable_entity }
end
end
end
# DELETE /statuses/1
# DELETE /statuses/1.json
def destroy
#activity = Activity.find_by_targetable_id(params[:id])
if #activity
#activity.destroy
end
#status.destroy
respond_to do |format|
format.html { redirect_to :back }
format.json { head :no_content }
end
end
private
def find_member
#member = Member.find_by_user_name(params[:user_name])
end
def find_status
#status = current_member.statuses.find(params[:id])
end
def sortable_date
created_at
end
end
Should not this line
#status = Activity.targetable
be
#status = #activity.targetable
?
Second note: it probably will be better to move status destroying to Activity model before_destroy callback.
I want my visitors to be able to edit or delete their comment up too 5-10 min after they created it.
How should I authenticate this with a session or cookie?
My comment controller:
class CommentsController < ApplicationController
# GET /comments
# GET /comments.xml
# GET /comments/new
# GET /comments/new.xml
def new
#comment = Comment.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => #comment }
end
end
# GET /comments/1/edit
def edit
#comment = Comment.find(params[:id])
end
# POST /comments
# POST /comments.xml
def create
#blog = Blog.find(params[:blog_id])
params[:comment][:ip] = request.remote_ip
#comment = #blog.comments.create!(params[:comment])
redirect_to #blog
end
# PUT /comments/1
# PUT /comments/1.xml
def update
#comment = Comment.find(params[:id])
respond_to do |format|
if #comment.update_attributes(params[:comment])
format.html { redirect_to(admin_comments_path, :notice => 'Comment was successfully updated.') }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => #comment.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /comments/1
# DELETE /comments/1.xml
def destroy
#comment = Comment.find(params[:id])
#comment.destroy
respond_to do |format|
format.html { redirect_to(admin_comments_url, :notice => 'Indlæg slettet') }
format.xml { head :ok }
end
end
end
store the saved comment's id in the session and then at the time of delete or update, check the session for the comment's id and compare the current-time with the comment's created_at... this can go in a filter method.
Also, you can move the code of finding the comment with id in a filter and can follow DRY.
Here it goes:
class CommentsController < ApplicationController
before_filter :get_blog
before_filter :get_comment, :only => [:edit, :update, :destroy]
before_filter :authorize_comment, :only => [:edit, :update, :destroy]
private
def get_blog
#blog = Blog.find(params[:blog_id])
end
def get_comment
#comment = Comment.find(params[:id])
end
def authorize_comment
unless #comment
flash[:error] = "Comment Not Found"
redirect_to #blog and return
else
# checks whether the comment is there in sessions' recent_comments
# if true, it means, this comment was created by the same visitor who is now attempting to delete/update it again
if session[:recent_comments].include?(#comment.id)
# now check if the comment is editable w.r.t time or not
if #comment.created_at < 10.minutes.ago
# if true, it means comment can no longer be updated/deleted
# if you wish you can now remove this from the session's recent_comments
session[:recent_comments].delete(#comment.id)
flash[:error] = "Sorry, you can not change this comment now"
redirect_to #blog and return
else
# it means comment can be edited/updated
return true
end
else
flash[:error] = "Sorry, you can not change this comment now"
redirect_to #blog and return
end
end
end
public
def new
#comment = Comment.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => #comment }
end
end
def edit
end
def create
params[:comment][:ip] = request.remote_ip
#comment = #blog.comments.create!(params[:comment])
unless session[:recent_comments].is_a?(Array)
session[:recent_comments] = []
end
session[:recent_comments] << #comment.id
redirect_to #blog
end
def update
respond_to do |format|
if #comment.update_attributes(params[:comment])
format.html { redirect_to(admin_comments_path, :notice => 'Comment was successfully updated.') }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => #comment.errors, :status => :unprocessable_entity }
end
end
end
def destroy
#comment.destroy
respond_to do |format|
format.html { redirect_to(admin_comments_url, :notice => 'Indlæg slettet') }
format.xml { head :ok }
end
end
end