Strong Parameters claims param not found when it's present - ruby

So for some reason I'm getting the ActionController::ParameterMissing error. It says incident parameter is missing however it's clearly present:
Started PATCH "/incidents/16/assign-score" for 127.0.0.1 at 2013-11-23 23:07:12 -0500
Processing by IncidentsController#update_override_score as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"RSGaHrrTrO5DoX8dVEtVNQX8OJnRAD35YRSCAvZtNr4=", "incident"=>{"id"=>"16", "score_override"=>"5"}, "commit"=>"Save legitimacy score", "id"=>"16"}
Unpermitted parameters: id, score_override
Incident Load (0.1ms) SELECT "incidents".* FROM "incidents" WHERE "incidents"."id" = ? LIMIT 1 [["id", "16"]]
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1
CACHE (0.0ms) SELECT "incidents".* FROM "incidents" WHERE "incidents"."id" = ? LIMIT 1 [["id", "16"]]
Completed 400 Bad Request in 9ms
ActionController::ParameterMissing (param not found: incident):
app/controllers/incidents_controller.rb:66:in `update_override_score'
Rendered /Users/justinbull/.rvm/gems/ruby-2.0.0-p247/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/_source.erb (0.6ms)
Rendered /Users/justinbull/.rvm/gems/ruby-2.0.0-p247/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.0ms)
Rendered /Users/justinbull/.rvm/gems/ruby-2.0.0-p247/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (1.0ms)
Rendered /Users/justinbull/.rvm/gems/ruby-2.0.0-p247/gems/actionpack-4.0.0/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (62.8ms)
Relevant controller code:
class IncidentsController < ApplicationController
load_and_authorize_resource
before_action :set_incident, only: [:show, :edit, :update, :destroy, :edit_override_score, :update_override_score]
# ...
def update_override_score
override_params = params.require(:incident).permit(:score_override)
override_params[:score_override] = nil if override_params[:score_override].blank?
respond_to do |format|
if #incident.update_attributes! score_override: override_params[:score_override]
format.html { redirect_to #incident, notice: 'Incident was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit_override_score' }
format.json { render json: #incident.errors, status: :unprocessable_entity }
end
end
end
# ...
private
# Use callbacks to share common setup or constraints between actions.
def set_incident
#incident = Incident.find(params[:id])
end
end
Any idea how this could possibly happen? You can see the incident hash right in the Parameters line of the log.

Thanks to Josh Leitzel, he pointed me in the right direction. I'm using the CanCan gem which is, at 1.6.10, has trouble with Rails 4. His comment explains the workaround.
I had to move the param.require() logic into a controller method incident_params however.

Related

how to insert image field on reply form in forum app en ruby on rails?

i try to add the image field on reply form in my new app type forum.
the app containt the principal sujet and all users connected can reply on section replie.
now , i try to add the image field more older text field.
i use carrierwave to implement the feature.
but i receives this error message in terminal:
NoMethodError - undefined method `reimage_will_change!' for #
<Reply:0x000055cb9f2abc30>
Did you mean? Reimage_will_change!:
app/controllers/replies_controller.rb:8:in `create'
why subjection rails: reimage_will_change:
my i used "reimage" that variable field.
see complet message termianl:
Started POST "/discussions/pourquoi-intel-a-t-il-du-mal-a-suivre-la-loi-de-moore-la-loi-de-moore-est-elle-morte/replies" for ::1 at 2019-07-04 10:12:20 +0000
(1.5ms) SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
↳ /home/chatln/.rbenv/versions/2.6.1/lib/ruby/gems/2.6.0/gems/activerecord-5.2.3/lib/active_record/log_subscriber.rb:98
Processing by RepliesController#create as JS
Parameters: {"utf8"=>"✓", "reply"=>{"reply"=>"Amazon CEO Jeff Bezos gave this advice to those ", "reimage"=>#<ActionDispatch::Http::UploadedFile:0x000055d560cc1150 #tempfile=#<Tempfile:/tmp/RackMultipart20190704-14120-1uwpx6n.png>, #original_filename="Capture d’écran de 2019-06-10 11-08-07.png", #content_type="image/png", #headers="Content-Disposition: form-data; name=\"reply[reimage]\"; filename=\"Capture d\xE2\x80\x99\xC3\xA9cran de 2019-06-10 11-08-07.png\"\r\nContent-Type: image/png\r\n">}, "commit"=>"Envoyer", "discussion_id"=>"pourquoi-intel-a-t-il-du-mal-a-suivre-la-loi-de-moore-la-loi-de-moore-est-elle-morte"}
User Load (1.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 1], ["LIMIT", 1]]
↳ /home/chatln/.rbenv/versions/2.6.1/lib/ruby/gems/2.6.0/gems/activerecord-5.2.3/lib/active_record/log_subscriber.rb:98
Discussion Load (0.8ms) SELECT "discussions".* FROM "discussions" WHERE "discussions"."slug" = $1 LIMIT $2 [["slug", "pourquoi-intel-a-t-il-du-mal-a-suivre-la-loi-de-moore-la-loi-de-moore-est-elle-morte"], ["LIMIT", 1]]
####
↳ app/controllers/replies_controller.rb:55
Completed 500 Internal Server Error in 225ms (ActiveRecord: 24.9ms)
####
NoMethodError - undefined method `reimage_will_change!' for #<Reply:0x00007ffb6c716fa0>
Did you mean? Reimage_will_change!:
app/controllers/replies_controller.rb:8:in `create'
I think the error comes from line 55 of the replies controller at the level of set_discussion.
def set_discussion
#discussion = Discussion.friendly.find(params[:discussion_id])
end
and replies_controller complet
class RepliesController < ApplicationController
before_action :authenticate_user!
before_action :set_reply, only: [:edit, :update, :show, :destroy]
before_action :set_discussion, only: [:create, :edit, :show, :update, :destroy]
#before_action :find_discussions, only: [:create, :edit, :show, :update, :destroy]
def create
#reply = #discussion.replies.create(params[:reply].permit(:reply, :reimage, :discussion_id))
#reply.user_id = current_user.id
respond_to do |format|
if #reply.save
format.html { redirect_to discussion_path(#discussion) }
format.js # renders create.js.erb
else
format.html { redirect_to discussion_path(#discussion), notice: "Reponse non enregistrée, ressayer encore."}
format.js
end
end
end
def new
end
def destroy
#reply = #discussion.replies.find(params[:id])
#reply.destroy
redirect_to discussion_path(#discussion)
end
def edit
#discussion = Discussion.find(params[:discussion_id])
#reply = #discussion.replies.find(params[:id])
end
def update
#reply = #discussion.replies.find(params[:id])
respond_to do |format|
if #reply.update(reply_params)
format.html { redirect_to discussion_path(#discussion), notice: 'Reponse mise a jour...' }
else
format.html { render :edit }
format.json { render json: #reply.errors, status: :unprocessable_entity }
end
end
end
def show
end
private
def set_discussion
#discussion = Discussion.friendly.find(params[:discussion_id])
end
def set_reply
#reply = Reply.find(params[:id])
end
def reply_params
params.require(:reply).permit(:reply, :reimage, :discussion_id)
end
end
and model replies
class Reply < ApplicationRecord
mount_uploader :reimage, ReimageUploader
belongs_to :discussion
belongs_to :user
validates :reply, presence: true
extend FriendlyId
friendly_id :reply, use: [:slugged, :finders]
def should_generate_new_friendly_id?
reply_changed?
end
end
undefined method `x_will_change!' for # occures if you forget to add a column in your model's db table. If you have a model Reply and a ReimageUploader, with the uploader mounted as in the Carrierwave docs:
class Reply < ActiveRecord::Base
mount_uploader :reimage, ReimageUploader
end
Then the error will read
undefined method `reimage_will_change!' for #
To fix it add a column in a migration run the following in the console:
rails g migration AddReimageToUsers reimage:string
This will generate the following migration:
class AddReimageToUsers < ActiveRecord::Migration
def change
add_column :replies, :reimage, :string
end
end
Migrate it to apply the change (write down the below command in the console):
rake db:migrate

Rails 5 Scheduling App Find all shifts for a user

We are attempting to create an endpoint that allows for a user to view all of their personal shifts across all calendars. Currently I have the following syntax in the shifts controller:
def myschedule
#user = current_user
if #user
#shifts = Shift.where("end_time > ?", Time.current).order("start_time ASC").limit(100)
render "/shifts/index2.json", status: :ok
else
render json: ('You do not have access to these shifts'), status: :unauthorized
end
end
This as expected is returning the first 100 shifts across all calendars, but for all users. What would be the best direction to search for a way to limit the shifts to just the ones for a specified user. I would appreciate some guidance in the right direction. The json rendered is an array of hashes.
As far as relations go on the model level:
a shift has_many users, through usershifts
a user has_many shifts, through usershifts
both user and shift has_many usershifts
and usershift belongs_to both user and shift.
I attempted:
def myschedule
#user = current_user
if #user
#shifts = Shift.where("end_time > ?", Time.current).order("start_time ASC").limit(100).include?(#user)
render "/shifts/index2.json", status: :ok
else
render json: ('You do not have access to these shifts'), status: :unauthorized
end
end
Which returned undefined method map for false: Falseclass in my json view.
Here is the json view as well:
json.shifts #shifts do |shift|
json.shift_id shift.id
json.start_time shift.start_time
json.end_time shift.end_time
json.calendar_name shift.calendar.name
end
I also tried to throw a .joins(#user) to the end of #shifts, that returned an unknown class User for the json.
Also I attempted:
def myschedule
if current_user
#shifts = Shift.where("end_time > ?", Time.current).order("start_time ASC").limit(100).where(:user_id => params[:user_id])
render "/shifts/index2.json", status: :ok
else
render json: ('You do not have access to these shifts'), status: :unauthorized
end
end
which gave the following error in server log
ActionView::Template::Error (PG::UndefinedColumn: ERROR: column
shifts.user_id does not exist
LINE 1: ...ERE (end_time > '2018-10-13 14:52:02.693352') AND "shifts"."
What would be the best direction to search for a way to limit the
shifts to just the ones for a specified user
This should work
#shifts = #user.shifts.where("end_time > ?", Time.current).order("start_time ASC").limit(100)

How do I get Devise 3.4 to permit Parameters Rails 4.2

Suggestions on how to improve this question are welcome
I added 3 things to the Devise user after generating it.
t.integer "role"
t.string "firstname"
t.string "lastname"
At User Signup these parameters are permitted and user is created correctly.
When a user tries to edit their account the "firstname" and "lastname" values can be changed fine but when a user tries to change their role on their /users/edit page, no error is given, flash says "account updated successfully" but the role value have not changed.
From /log/development.log showing all 3 parameters as unpermitted, if this really is the case I don't know why the other two can be updated.
Parameters: {"utf8"=>"✓", "authenticity_token"=>"LnVPFFJKV+RtnB21ZUGr4HF1siVcEuT/BRXaLVkch1nWQXiGRFVGhdWchlQSZ9A7mFgKX2njEjCbqR4CHp5hmQ==", "user"=>{"role"=>"worker", "firstname"=>"asdfDe Wet", "lastname"=>"Blomerus", "email"=>"dewet#blomerus.org", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "current_password"=>"[FILTERED]"}, "commit"=>"Update"}
[1m[36mUser Load (0.8ms)[0m [1mSELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT 1[0m [["id", 6]]
[1m[35mUser Load (0.4ms)[0m SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 6]]
Unpermitted parameters: role, firstname, lastname
Redirected to http://localhost:3000/
Completed 302 Found in 84ms (ActiveRecord: 1.5ms)
/config/initializers/devise_permitted_parameters.rb
module DevisePermittedParameters
extend ActiveSupport::Concern
included do
before_filter :configure_permitted_parameters
end
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) << [:firstname, :lastname, :role]
devise_parameter_sanitizer.for(:account_update) << [:firstname, :lastname, :role]
end
end
DeviseController.send :include, DevisePermittedParameters
Relevant parts of /app/controllers/users_controller.rb
def update
#user = User.find(params[:id])
if #user.update_attributes(secure_params)
redirect_to users_path, :notice => "User updated."
else
redirect_to users_path, :alert => "Unable to update user."
end
end
private
def secure_params
params.require(:user).permit(:role, :firstname, :lastname)
end
The update action never runs, I can completely comment it out and nothing changes.
This is what works for me with devise:
I change the users/registrations_controller.rb
class Users::RegistrationsController < Devise::RegistrationsController
before_action :configure_permitted_parameters, only: [:create]
before_filter :configure_account_update_params, only: [:update]
def create
super
end
# GET /resource/edit
def edit
super
end
# PUT /resource
def update
super
end
# DELETE /resource
def destroy
super
end
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) do |u|
u.permit(:first_name, :last_name, :user_name, :email, :password, :password_confirmation, :avatar, :avatar_cache)
end
end
def configure_account_update_params
devise_parameter_sanitizer.for(:account_update)do |u|
u.permit(:first_name, :last_name, :user_name, :email, :password, :password_confirmation, :current_password, :avatar, :avatar_cache)
end
end
I don't define any update action in the users_controller.rb . It is not needed. Also, I don;t use any type of module that you are defining and it works fine.

expiring action from a different controller

I have two controllers like this
class New::StoresController < ApplicationController
caches_action :index, cache_path: Proc.new {|c| c.params}, expires_in: cache_time(:long)
caches_action :show, cache_path: Proc.new {|c| c.params}, expires_in: cache_time(:long)
def index
end
def show
# Here I use param[:store], params[:locale] and params[:ref]
end
end
class New::StoreReviewsController < ApplicationController
def create
expire_action controller: '/new/stores', action: :show, \
store:params[:store], locale:"en", ref:"stores"
end
end
I want to expire action New::StoresController#show on creation of a new StoreReview.
When the show action of Store is executed, the cache reads the following
Cache read: views/localhost:3000/en/stores/store-name
Read fragment views/localhost:3000/en/stores/store-name
While expire_action expires this fragment
Expire fragment views/localhost:3000/en/search?action=show&controller=new/stores&ref=stores
Cache delete: views/localhost:3000/en/search?action=show&controller=new/stores
The question is should I use expire_fragment instead of expire_action as mentioned here ? rails 3 caching: expire action for named route
Also if I want to cache the action but not with all params what is the best way to do it?
Currently that's what I am doing
caches_action :show, cache_path: Proc.new {|c| c.params.select{ |p| [:controller,:action ,"locale", "store"].include? p} }, expires_in: cache_time(:long)
I've got the answer for that.
By default caches_action ignores parameters.
And for getting the right fragment to be expired I did the following
expire_action store_url(host: my_host, store: store_name, locale: locale])

nil method error on omniauth.auth

def create
5 debugger
6 auth=request.env["omniauth.auth"]
=> 7 user=Moviegoer.find_by_provider_and_uid(auth["provider"],auth["uid"]) ||
8 Moviegoer.create_with_omniauth(auth)
9 session[:user_id] = user.id
10 redirect_to movies_path
The above code is from the controller action (create) - i ran with debugger on;
I am getting 'nil' value for auth variable - i had omniauth in gem file and bundle installed it...still not able to get the above statement executed right...am i missing something here...?
------
I tried few things and progressed few steps -but still stuck at an error
Started GET "/auth/twitter" for 127.0.0.1 at 2013-12-28 17:38:26 -0800
Timeout::Error (execution expired):
The code in application controller is :
class ApplicationController < ActionController::Base
before_filter :set_current_user
protected # prevents method from being invoked by a route
def set_current_user
debugger
# we exploit the fact that find_by_id(nil) returns nil
#current_user ||= Moviegoer.find_by_id(session[:user_id])
redirect_to '/auth/twitter' and return unless #current_user
end
end
I believe the code is timing out at redirect_to statement...
You should map your oauth callback to your create action.
# config/routes.rb
match '/auth/:provider/callback' => 'authentications#create'

Resources