I'm currently doing this
class DetailsController < ApplicationController
def create
#detail = Detail.new(params.require(:detail).permit(:user_id, :note))
if #detail.save
redirect_to #detail
else
render 'new'
end
end
def update
#detail = Detail.find(params[:id])
if #detail.update(detail_params)
redirect_to #detail
else
render 'edit'
end
end
private
def detail_params
params.require(:detail).permit(:note)
end
end
Is it possible too chain strong parameters in Rails? I tried doing this but it didn't work
class DetailsController < ApplicationController
def create
#detail = Detail.new(detail_params.permit(:user_id))
if #detail.save
redirect_to #detail
else
render 'new'
end
end
def update
#detail = Detail.find(params[:id])
if #detail.update(detail_params)
redirect_to #detail
else
render 'edit'
end
end
private
def detail_params
params.require(:detail).permit(:note)
end
end
To DRY things up I have used the tap method and done something like this...
def detail_params(is_create = false)
params.require(:detail).permit(:note).tap do |p|
p[:user_id] = current_user.id if is_create
end
end
def create
#detail = Detail.new(detail_params(true))
if #detail.save
redirect_to #detail
else
render 'new'
end
end
def update
#detail = Detail.find(params[:id])
if #detail.update(detail_params)
redirect_to #detail
else
render 'edit'
end
end
To just have different sets of parameters, this works...
def detail_params(is_create = false)
permitted = [:note]
permitted << :user_id if is_create
params.require(:detail).permit(permitted)
end
Related
I am a newbie when it comes to RubyOnRails. Recently while working with the gem pundit I encountered a problem. Pundit during function sort? authorization does not see the logged in user that is #user = nill. I don't know what the problem is because other authorizations with the same syntax works for example edit? I am uploading the code below:
lesson_controler.rb
class LessonsController < ApplicationController
before_action :set_lesson, only: [ :show, :edit, :update, :destroy ]
def sort
#course = Course.friendly.find(params[:course_id])
#lesson = Lesson.friendly.find(params[:lesson_id])
authorize #lesson
#lesson.update(lesson_params)
render body: nil
end
def index
#lessons = Lesson.all
end
def show
authorize #lesson
current_user.view_lesson(#lesson)
#lessons = #course.lessons
end
def new
#lesson = Lesson.new
#course = Course.friendly.find(params[:course_id])
end
def edit
authorize #lesson
end
def create
#lesson = Lesson.new(lesson_params)
#course = Course.friendly.find(params[:course_id])
#lesson.course_id = #course.id
authorize #lesson
respond_to do |format|
if #lesson.save
format.html { redirect_to course_lesson_path(#course,#lesson), notice: "Lesson was successfully created." }
format.json { render :show, status: :created, location: #lesson }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: #lesson.errors, status: :unprocessable_entity }
end
end
end
def update
authorize #lesson
respond_to do |format|
if #lesson.update(lesson_params)
format.html { redirect_to course_lesson_path(#course,#lesson), notice: "Lesson was successfully updated." }
format.json { render :show, status: :ok, location: #lesson }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: #lesson.errors, status: :unprocessable_entity }
end
end
end
def destroy
authorize #lesson
#lesson.destroy
respond_to do |format|
format.html { redirect_to course_path(#course), notice: "Lesson was successfully destroyed." }
format.json { head :no_content }
end
end
private
def set_lesson
#course = Course.friendly.find(params[:course_id])
#lesson = Lesson.friendly.find(params[:id])
end
def lesson_params
params.require(:lesson).permit(:title, :content, :row_order_position)
end
end
lesson_policy.rb:
class LessonPolicy < ApplicationPolicy
class Scope < Scope
def resolve
scope.all
end
end
def sort?
#record.course.user_id == #user.id
end
def edit?
#record.course.user_id == #user.id
end
def update?
#record.course.user_id == #user.id
end
def destroy?
#record.course.user_id == #user.id
end
def show?
#record.course.user_id == #user.id || #user&.has_role?(:admin) || #record.course.bought(#user) == false
end
def new?
#record.course.user_id == #user.id
end
def create?
#record.course.user_id == #user.id
end
end
Application_policy.rb:
class ApplicationPolicy
attr_reader :user, :record
def initialize(user, record)
#user = user
#record = record
end
def index?
false
end
def show?
false
end
def create?
false
end
def new?
create?
end
def update?
false
end
def edit?
update?
end
def destroy?
false
end
class Scope
def initialize(user, scope)
#user = user
#scope = scope
end
def resolve
scope.all
end
private
attr_reader :user, :scope
end
end
Console logs
How can I make a logged in user visible to pundit?
I am trying to create a session for a model called Commuter by defining a helper method in application_controller.rb file. As follows.
application_controller.rb
helper_method :current_commuter
def current_commuter
#commuter ||= Commuter.find session[:cid]
end
After verifying the commuter's phone number I am trying to create a
login session.
commuters_controller.rb
def verify
#commuter = Commuter.where(phone_number: params[:phone_number]).first
if (#commuter && #commuter.authenticate_otp(params[:otp],drift:300))
#commuter.auth_active = true
if #commuter.save
#Removed from session after verified it
session[:phone_number] = nil
session[:is_verified] = nil
#signed in commuter after verified it
sign_in(:commuter, #commuter)
flash[:notice] = "Your mobile no is verified."
end
else
flash[:alert] = "You have entered wrong otp.Please check again."
end
puts "#{current_commuter.phone_number}"
redirect_to root_path
end
I put a puts to check if the current_commuter is working or not. It is when I checked on the console. Now when I added few links on a view file as follows:
app/views/bookings/outstation.html.erb
<%if current_commuter.present? %>
<li> <%= link_to "Dashboard", dashboard_commuters_path %> </li>
<li> <%= link_to "Logout", destroy_commuter_session_path, method: :delete%></li>
<%else%>
<li>
<a href="" data-toggle="modal" data-target="#signinmodal">
REGISTER | LOGIN
</a>
</li>
<%end%>
Now I am getting the following error:
ActiveRecord::RecordNotFound in BookingsController#outstation
Couldn't find Commuter without an ID
EDIT
bookings_controller.rb
class BookingsController < ApplicationController
layout 'bookings'
before_action :set_ride_later_request_from_ref_id, only:[
:select_vehicle, :update_vehicle_details,
:contact_details,:complete_booking_request]
before_action :set_ride_later_request_from_uuid_ref, only:[
:request_quotations,:quotations, :confirm_booking,
:confirmation
]
before_action :set_trip_type, only: [:outstation, :local_booking]
def new_booking
#ride_later_request = RideLaterRequest.new
#vahicle = RideLaterRequest.new
end
def create_ride_later_request
#ride_later_request = RideLaterRequest.new(permitted_attributes(RideLaterRequest))
respond_to do |format|
if #ride_later_request.save
format.html {redirect_to bookings_select_vehicle_path(ref_id: #ride_later_request.rlr_ref_code.content)}
else
format.html {render :outstation}
end
end
end
def update_vehicle_details
respond_to do |format|
if #ride_later_request.update(permitted_attributes(RideLaterRequest))
format.html {redirect_to bookings_contact_details_path(ref_id:#ride_later_request.rlr_ref_code.content)}
else
format.html {render :select_vehicle}
end
end
end
def contact_details
end
def complete_booking_request
#operation = nil
if params[:get_otp].nil? && params[:get_quotations].nil?
render json:{error:"Wrongly formed request"}, status: 422
end
if params[:get_otp]
#operation = :get_otp
if #ride_later_request.update(permitted_attributes(RideLaterRequest))
SMSSender.send_otp_message(#ride_later_request.phone_number,#ride_later_request.otp_code)
return
else
render json:{error:#ride_later_request.errors.full_messages[0]}, status: 422
end
elsif params[:get_quotations]
#operation = :get_quotations
if (params[:ride_later_request][:otp].blank? ||
!#ride_later_request.authenticate_otp(params[:ride_later_request][:otp],drift:300))
render json:{error:"OTP is wrong"}, status: 422 and return
else
#ride_later_request.user_verified = true
if !#ride_later_request.save
render json:{error:#ride_later_request.errors.full_messages.first}, status:422 and return
end
if #ride_later_request.status == 'UnderConstruction'
render json:{error:"Some fields are missing. Please try again"}, status:422 and return
end
end
end
end
def request_quotations
request_loc = [#ride_later_request.pickup_lat,#ride_later_request.pickup_lng]
#rfq_agencies = #ride_later_request.rfq_agencies.sort_by{|l|l.distance_to(request_loc)}
#ride_later_quotes = #ride_later_request.ride_later_quotes.to_a
#ride_later_quotes.sort!{|a,b| a.total_payable.to_i <=> b.total_payable.to_i}
end
def quotations
#ride_later_quotes = #ride_later_request.ride_later_quotes.to_a
#ride_later_quotes.sort!{|a,b| a.total_payable.to_i <=> b.total_payable.to_i}
if session[:trip_type] == 'HourlyPackage'
render :local_booking_quotation
else
render :outstation_booking_quotations
end
end
def confirm_booking
if #ride_later_request.status=='Unfulfilled' ||
#ride_later_request.status=='Rejected' ||
#ride_later_request.status=='Ignored'
render json:{error:'Trip request has expired. Start a new booking.'}, status:422 and return
end
if #ride_later_request.status=="Cancelled"
render json:{error:'Trip request has been cancelled. Start a new booking.'}, status:422 and return
end
if #ride_later_request.status!="QuotesReady"
render json:{error:'Trip request is in wrong state. Start a new booking.'}, status:422 and return
end
#quote = #ride_later_request.ride_later_quotes.find(params[:quote_id]) rescue nil
if #quote.blank?
render json:{error:'Quotation not linked to this trip'}, status:422 and return
end
if #quote.status != 'Submitted'
render json:{error: "Quote is in wrong state #{#quote.status}. Start a new booking"}, status:422 and return
end
#quote.status = 'Accepted'
if !#quote.save
render json:{error:#quote.errors.full_messages.first}, status:422 and return
end
RideLaterRequestHandler.commuter_accepts_quote(#quote)
end
def confirmation
#ride = #ride_later_request.ride_later_ride
#quote = #ride.ride_later_quote
end
def set_ride_later_request_from_ref_id
#ref_id = params[:ref_id]
#ride_later_request = RlrRefCode.where(content:#ref_id).first.ride_later_request rescue nil unless #ref_id.blank?
if #ride_later_request.blank?
flash[:alert] = "Something went wrong. Please create new booking request."
redirect_to bookings_new_path
end
end
def set_ride_later_request_from_uuid_ref
#uuid = params[:booking_id]
#ride_later_request = RideLaterRequest.where(uuid_ref:#uuid).first rescue nil if #uuid.present?
if #ride_later_request.blank?
flash[:alert] = "Something went wrong. Please create new booking request."
redirect_to bookings_new_path
end
end
def select_vehicle
#ride_later_request = RlrRefCode.find_by_content(params[:ref_id]).ride_later_request
end
def vehicle_type_ac
if params[:booking_summary_id].present?
#ride_later_request = RideLaterRequest.find(params[:booking_summary_id])
else
#ride_later_request = RlrRefCode.find_by_content(params[:ride_later_request][:ref_id]).ride_later_request
#ride_later_request.update(vehicle_type: params[:ride_later_request][:vehicle_type], number_of_passengers: params[:ride_later_request][:number_of_passengers])
end
end
def vehicle_type
#ride_later_request = RlrRefCode.find_by_content(params[:ref_id]).ride_later_request
end
def outstation
#ride_later_request = RideLaterRequest.new(trip_type: 'Outstation')
end
def local_booking
#ride_later_request = RideLaterRequest.new(trip_type: params[:trip_type])
end
def bangalore_innova
#ride_later_request = RideLaterRequest.new(trip_type: 'Outstation')
end
def bangalore_outstation
#ride_later_request = RideLaterRequest.new(trip_type: 'Outstation')
end
def bangalore_taxi
#ride_later_request = RideLaterRequest.new(trip_type: 'Outstation')
end
def tt_for_rent
#ride_later_request = RideLaterRequest.new(trip_type: 'Outstation')
end
def minibus_for_rent
#ride_later_request = RideLaterRequest.new(trip_type: 'Outstation')
end
# def select_vehicle_local
# end
def about_us
end
def terms_conditions
end
def privacy_policy
end
def journey_way
#ride_later_request = RideLaterRequest.create(user_params)
#ride_later_request.save
respond_to do |format|
format.html {render :select_vehicle}
end
end
def outstation_booking_quotations
#ride_later_request = RideLaterRequest.find_by(id: params[:ride_later_request])
#ref_id = params[:ref_id]
end
def select_vehicle_outstation
#ride_later_request = RlrRefCode.find_by_content(params[:ref_id]).ride_later_request
redirect_to outstation_booking_quotations_path(#ride_later_request.rlr_ref_code.content, #ride_later_request )
end
def trip_summary
#ride_later_request = RlrRefCode.find_by_content(params[:ride_later_request][:ref_id]).ride_later_request
#ride_later_request.update(vehicle_type: params[:ride_later_request][:vehicle_type], number_of_passengers: params[:ride_later_request][:number_of_passengers])
puts "Ride LATER REQUEST LOG"
puts #ride_later_request
if #ride_later_request.update(additional_instructions: params[:ride_later_request][:additional_instructions], ac: 'AC')
render :template => 'bookings/booking_summary', :locals => {:ride_later_request => #ride_later_request, :ref_id => #ride_later_request.rlr_ref_code.content, :vehicle_type => params[:ride_later_request][:vehicle_type]}
else
format.html {render :index}
end
end
def user_params
params.require(:ride_later_request).permit(:pickup_area, :pickup_city, :destination_city, :pickup_lng, :pickup_lat)
end
def set_trip_type
session[:trip_type] = params[:trip_type]
end
end
It looks to me like the error's thrown here:
def current_commuter
#commuter ||= Commuter.find session[:cid]
end
Are you calling this as a before_action?
Using find raises an error if a record's not found, so I'd suggest you're either not passing in an id in session[:cid], or what you are passing doesn't match a Commuter in your db.
You can use find_by_id to avoid throwing an error (it returns nil if the record's not found), or work around this to ensure the method's only called where it should be.
Does that help?
Edit: Based on your additional info, this could be coming from any of the finds in the bookings_controller. Same explanation as above though :)
I'm using the pundit gem in order to give permissions to three different users(Admin, seller, viewer). Currently I got everything working, admin has access to everything, seller to his own products and viewer can just view the products.
The only glitch I'm having is that I would like the non signed_up/signed_in users to be able to view the products via search results. Right now non sign_up/signed_in users can see the search results but don't have access to the show view.
Here is the setup I have:
class ItemPolicy < ApplicationPolicy
attr_reader :item
def initialize(user, record)
super(user, record)
#user = user
#item = record
end
def update?
#user.is_a?(Admin) ? item.all : #user.items
end
def index?
#user.is_a?(Admin) ? item.all : #user.items
end
def show?
#user.is_a?(Admin) ? item.all : #user.items
end
def create?
#user.is_a?(Admin) ? item.all : #user.items
end
def new?
#user.is_a?(Admin) ? item.all : #user.items
end
def edit?
#user.is_a?(Admin) ? item.all : #user.items
end
def destroy?
#user.is_a?(Admin) ? item.all : #user.items
end
class Scope < Struct.new(:user, :scope)
def resolve
if user.is_a?(Admin)
scope.where(:parent_id => nil)
elsif user.is_a?(Seller)
scope.where(:id => user.items)
end
end
def show?
return true if user.is_a?(Admin)
return true if user.seller_id == seller.id && user.is_a?(Seller)
false
end
end
end
the controller:
class ItemsController < ApplicationController
before_action :set_item, only: [:show, :edit, :update, :destroy]
def index
authorize Item
#items = policy_scope(Item)
end
def search
if params[:term]
#items = Item.search(params[:term]).order("created_at DESC")
else
#items = []
end
end
def show
#comments = Comment.where(item_id: #item).order("created_at DESC")
#items = policy_scope(Item).find(params[:id])
authorize #item
end
def new
#item = Item.new
authorize #item
#categories = Category.order(:name)
end
def edit
authorize #item
#categories = Category.order(:name)
end
def create
#item = Item.new(item_params)
authorize #item
respond_to do |format|
if #item.save
format.html { redirect_to #item, notice: 'Item was successfully created.' }
format.json { render :show, status: :created, location: #item }
else
format.html { render :new }
format.json { render json: #item.errors, status: :unprocessable_entity }
end
end
end
def update
authorize #item
respond_to do |format|
if #item.update(item_params)
format.html { redirect_to #item, notice: 'Item was successfully updated.' }
format.json { render :show, status: :ok, location: #item }
else
format.html { render :edit }
format.json { render json: #item.errors, status: :unprocessable_entity }
end
end
end
def destroy
authorize #item
#item.destroy
respond_to do |format|
format.html { redirect_to items_url, notice: 'Item was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def set_item
#item = Item.find(params[:id])
authorize #item
end
def item_params
params.require(:item).permit(:title, :description, :image, :price, :category_id)
end
end
application_contoller.rb
class ApplicationController < ActionController::Base
include Pundit
protect_from_forgery prepend: true
rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
def pundit_user
current_seller || current_admin || current_viewer
end
private
def user_not_authorized(exception)
policy_name = exception.policy.class.to_s.underscore
flash[:warning] = t "#{policy_name}.#{exception.query}", scope: "pundit", default: :default
redirect_to(request.referrer || root_path)
end
end
Update 1
class ApplicationPolicy
attr_reader :user, :record
def initialize(user, record)
raise Pundit::NotAuthorizedError, "must be logged in" unless user
#user = user
#record = record
end
def index?
true # anybody can view
end
def show?
true # anybody can view
end
def search?
index?
end
def new?
create?
end
def edit?
update?
end
def destroy?
update?
end
private
# don't repeat yourself
def admin?
user.is_a?(Admin)
end
def seller?
user.is_a?(Seller)
end
end
class ItemPolicy < ApplicationPolicy
attr_reader :item
class Scope < Struct.new(:user, :scope)
def resolve
if admin?
scope.where(parent_id: nil)
elsif seller?
# avoids a query for user.items
scope.where(seller: user)
end
end
end
def initialize(user, record)
super(user, record)
#user = user
#item = record
end
def update?
admin? || is_owner?
end
def create?
# just guessing here
admin? || seller?
end
private
def is_owner?
# or whatever the association between the item and its owner is
item.seller == user
end
end
You are confusing scopes and the authorization methods in Pundit. The new?, show? etc. methods should return a boolean indicating if the user is allowed to perform the action at all.
To allow unauthorized users to perform an action you simply return true.
Scopes are used to narrow down which records the user has access to. They only have a resolve method.
class ApplicationPolicy
# ...
private
# don't repeat yourself
def admin?
user.is_a?(Admin)
end
def seller?
user.is_a?(Seller)
end
end
class ItemPolicy < ApplicationPolicy
attr_reader :item
class Scope < Struct.new(:user, :scope)
def resolve
if admin?
scope.where(parent_id: nil)
elsif seller?
# avoids a query for user.items
scope.where(seller: user)
end
end
end
def initialize(user, record)
super(user, record)
#user = user
#item = record
end
def update?
admin? || is_owner?
end
def index?
true # anybody can view
end
def show?
true # anybody can view
end
def search?
index?
end
def create?
# just guessing here
admin? || seller?
end
def new?
create?
end
def edit?
update?
end
def destroy?
update?
end
private
def is_owner?
# or whatever the association between the item and its owner is
item.seller == user
end
end
Instead of repeating yourself (the conditions) you can shortcut many of the actions since the permissions for editing for example is the same as updating. You can even do this in the ApplicationPolicy so that you don't have to repeat it in each policy class:
class ApplicationPolicy
# ...
def index?
true # anybody can view
end
def show?
true # anybody can view
end
def search?
index?
end
def new?
create?
end
def edit?
update?
end
def destroy?
update?
end
private
# don't repeat yourself
def admin?
user.is_a?(Admin)
end
def seller?
user.is_a?(Seller)
end
end
class ItemPolicy < ApplicationPolicy
attr_reader :item
class Scope < Struct.new(:user, :scope)
def resolve
if admin?
scope.where(parent_id: nil)
elsif seller?
# avoids a query for user.items
scope.where(seller: user)
end
end
end
def initialize(user, record)
super(user, record)
#user = user
#item = record
end
def update?
admin? || is_owner?
end
def create?
# just guessing here
admin? || seller?
end
private
def is_owner?
# or whatever the association between the item and its owner is
item.seller == user
end
end
You are also authorizing the user twice at many places in your controller as it is as already performed by the set_item callback:
class ItemsController < ApplicationController
before_action :set_item, only: [:show, :edit, :update, :destroy]
def index
authorize Item
#items = policy_scope(Item)
end
def search
if params[:term]
#items = Item.search(params[:term]).order("created_at DESC")
else
#items = Item.none # Don't use [] as #items.none? for example would blow up.
end
end
def show
#comments = Comment.where(item_id: #item).order("created_at DESC")
authorize #item
end
def new
#item = authorize(Item.new)
#categories = Category.order(:name)
end
def edit
#categories = Category.order(:name)
end
def create
#item = authorize(Item.new(item_params))
respond_to do |format|
if #item.save
format.html { redirect_to #item, notice: 'Item was successfully created.' }
format.json { render :show, status: :created, location: #item }
else
format.html { render :new }
format.json { render json: #item.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #item.update(item_params)
format.html { redirect_to #item, notice: 'Item was successfully updated.' }
format.json { render :show, status: :ok, location: #item }
else
format.html { render :edit }
format.json { render json: #item.errors, status: :unprocessable_entity }
end
end
end
def destroy
#item.destroy
respond_to do |format|
format.html { redirect_to items_url, notice: 'Item was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def set_item
#item = authorize( Item.find(params[:id]) )
end
def item_params
params.require(:item).permit(:title, :description, :image, :price, :category_id)
end
end
In my app I have a commenting system that's largely based off of this railscast. Now in my models I'm changing the to_param to a random string so the id isn't in the url. But then that breaks commenting.
status.rb
class Status < ActiveRecord::Base
attr_accessible :content, :member_id, :document_attributes, :permalink
belongs_to :member
belongs_to :document
has_many :comments, as: :commentable, dependent: :destroy
before_create :make_it_permalink
accepts_nested_attributes_for :document
def to_param
permalink
end
private
def make_it_permalink
# this can create permalink with random 12 digit alphanumeric
self.permalink = SecureRandom.hex(12)
end
end
statuses_controller.rb
class StatusesController < ApplicationController
before_filter :authenticate_member!, only: [:index, :new, :create, :destroy]
before_filter :find_member
rescue_from ActiveRecord::RecordNotFound do
render file: 'public/404', status: 404, formats: [:html]
end
def index
#statuses = Status.order('created_at desc').page(params[:page]).per_page(21)
respond_to do |format|
format.html # index.html.erb
format.js
end
end
def show
#status = Status.find_by_permalink(params[:id])
#commentable = #status
#comments = #commentable.comments.order('created_at desc').page(params[:page]).per_page(15)
#comment = #commentable.comments.new
respond_to do |format|
format.html # show.html.erb
format.json { redirect_to profile_path(current_member) }
end
end
def new
#status = Status.new
#status.build_document
respond_to do |format|
format.html # new.html.erb
format.json { render json: #status }
format.js
end
end
def create
#status = current_member.statuses.new(params[:status])
respond_to do |format|
if #status.save
#activity = current_member.create_activity(#status, 'created')
format.html { redirect_to :back }
format.json
format.js
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 }
format.js
end
end
end
def destroy
#status = current_member.statuses.find(params[:id])
#activity = Activity.find_by_targetable_id(params[:id])
#commentable = #status
#comments = #commentable.comments
if #activity
#activity.destroy
end
if #comments
#comments.destroy
end
#status.destroy
respond_to do |format|
format.html { redirect_to profile_path(current_member) }
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_by_permalink(params[:id])
end
end
comments_controller.rb
class CommentsController < ApplicationController
before_filter :authenticate_member!
before_filter :load_commentable
before_filter :find_member
def index
redirect_to root_path
end
def new
#comment = #commentable.comments.new
end
def create
#comment = #commentable.comments.new(params[:comment])
#comments = #commentable.comments.order('created_at desc').page(params[:page]).per_page(15)
#comment.member = current_member
respond_to do |format|
if #comment.save
format.html { redirect_to :back }
format.json
format.js
else
format.html { redirect_to :back }
format.json
format.js
end
end
end
def destroy
#comment = Comment.find(params[:id])
respond_to do |format|
if #comment.member == current_member || #commentable.member == current_member
#comment.destroy
format.html { redirect_to :back }
format.json
format.js
else
format.html { redirect_to :back, alert: 'You can\'t delete this comment.' }
format.json
format.js
end
end
end
private
# def load_commentable
# resource, id = request.path.split('/')[1,2] # photos/1/
# #commentable = resource.singularize.classify.constantize.find(id) # Photo.find(1)
# end
# alternative option:
def load_commentable
klass = [Status, Medium, Project, Event, Listing].detect { |c| params["#{c.name.underscore}_id"] }
#commentable = klass.find(params["#{klass.name.underscore}_id"])
end
#def load_commentable
# #commentable = params[:commentable_type].camelize.constantize.find(params[:commentable_id])
#end
def find_member
#member = Member.find_by_user_name(params[:user_name])
end
end
The problem lies in the load_commentable method in the comments_controller. I've tried a couple different variations of the method but the second one works best for my app and it was working when the url's had their id's in them. But since I overwrote the to_param to use my random permalink commenting stopped working because it's trying to find theid where it equals the permalink. Since it seems to try to find the id through the url, how do I pass the the actual id and not the permalink or how do I find commentable by it's permalink instead of id?
It's hard to tell if your param will always be the value of id or always be the permalink, or will sometimes be an id and sometimes a permalink.
If it will always be a permalink, then do:
#commentable = klass.find_by_permalink(params["#{klass.name.underscore}_id"])
instead of
#commentable = klass.find(params["#{klass.name.underscore}_id"])
If it is sometimes id and sometimes other, then you will need make logic to determine which is needed based on the class.
class CommentsController < ApplicationController
def create
#contact = Contact.find(params[:contact_id])
#comment = #contact.comments.create(params[:comment])
respond_to do |format|
format.html { redirect_to contact_path(#contact) }
format.js
end
end
def destroy
#contact = Contact.find(params[:contact_id])
#comment = #contact.comments.find(params[:id])
#comment.destroy
respond_to do |format|
format.html { redirect_to contact_path(#contact) }
format.js
end
end
end
Is it possible to also create and destroy comments for the company model? How do you check whether a user is on a certain page? Because then I can just have an if statement.
The changed CommentsController
class CommentsController < ApplicationController
def create
#object = find_object
#comment = #object.comments.create(params[:comment])
respond_to do |format|
format.html { redirect_to [#object] }
format.js
end
end
def destroy
#object = find_object
#comment = object.comments.find(params[:id])
#comment.destroy
respond_to do |format|
format.html { redirect_to [#object] }
format.js
end
end
private
def object
#object = if params[:contact_id]
Contact.find(params[:contact_id]
elsif params[:company_id]
Company.find(params[:company_id])
end
end
end
you can do it with routing
# routes.rb
resources :contacts do
resources :comments
end
resources :company do
resources :comments
end
So in controller you can handle if there any company or contact around:
def destroy
#object = find_object
#comment = #object.comments.find(params[:id])
#comment.destroy
redirect_to [#object]
end
private
def find_object
#object = if params[:contact_id]
Contact.find(params[:contact_id])
elsif params[:company_id]
Company.find(params[:company_id])
end
end
But best solution here is to use POLYMORPHISM here. Check out:
http://railscasts.com/episodes/154-polymorphic-association