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

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

Related

Pundit with second devise model

I manage the authorization of users in my app with the pundit gem. Everything works fine for the user. Now I created a second devise model: Employers. I want to show a specific page to both logged in user as well as logged in employers. How do I do that?
Here is my policy for the model:
class CurriculumPolicy < ApplicationPolicy
class Scope < Scope
def resolve
scope.all
end
end
def create?
return true
end
def show?
record.user == user || user.admin
end
def update?
record.user == user || user.admin
end
def destroy?
record.user == user || user.admin
end
end
And here is my controller for the index page which I want to make accessible:
class CurriculumsController < ApplicationController
skip_before_action :authenticate_user!, only: [:new, :create, :index]
before_action :set_curriculum, only: [:show, :edit, :update, :destroy]
def index
# #curriculums = policy_scope(Curriculum).order(created_at: :desc)
if params[:query]
#curriculums = policy_scope(Curriculum).joins(:user)
.where('users.job_category ILIKE ?', "%#{params[:query]}%")
.where(
'job_category ILIKE :query', query: "%#{params[:query]}%"
)
else
#curriculums = policy_scope(Curriculum).order(created_at: :desc)
end
end
private
def set_curriculum
#curriculum = Curriculum.find(params[:id])
end
def curriculum_params
params.require(:curriculum).permit(:doc)
end
end
You can have workaround here like below for each actions
def show?
true if #user.class.table_name == "employees"
end

irb does not have access to my models (NameError: uninitialized constant)

I am receiving this error when trying to create a new 'Pin' in IRB. For example:
irb(main):001:0> #pin = Pin.first
NameError: uninitialized constant Pin
OR
irb(main):001:0> #pin = Pin.new
NameError: uninitialized constant Pin
I must of changed something as it was working before. Unfortunately, I cannot find the error
Here is my pins controller:
class PinsController < ApplicationController
before_action :authenticate_user!, except: [:index, :show]
before_action :correct_user, only: [:edit, :update, :destroy]
before_action :set_pin, only: [:show, :edit, :update, :destroy]
def index
#pins = Pin.all
end
def show
#pin = Pin.find params[:id]
end
def new
#pin = Pin.new
end
def edit
end
def create
#pin = Pin.new(pin_params)
if #pin.save
redirect_to #pin, notice: 'Pin was successfully created.'
else
render action: 'new'
end
end
def update
if #pin.update(pin_params)
redirect_to #pin, notice: 'Pin was successfully updated.'
else
render action: 'edit'
end
end
def destroy
#pin.destroy
redirect_to pins_url
end
private
# Use callbacks to share common setup or constraints between actions.
def set_pin
#pin = Pin.find(params[:id])
end
def correct_user
#pin = current_user.pins.find(params[:id])
redirect_to pins_path, notice: "Not allowed!" if #pin.nil?
end
# Never trust parameters from the scary internet, only allow the white list through.
def pin_params
params.require(:pin).permit(:description)
end
end
Here is are my associations, pin.rb
class Pin < ApplicationRecord
belongs_to :user
end
And my associations for User.rb:
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :pins
end
and my routes
Rails.application.routes.draw do
resources :pins
devise_for :users
root "pages#home"
get "about" => "pages#about"
end
irb does not automatically load your Rails environment, which is why it does not have access to your models (or helpers, or database, or anything else). However, the "rails console" is an irb session that does load all of your Rails classes, database connections, etc.
To start the rails console:
rails c
Which is shorthand for:
rails console
This starts the rails console for your development environment. You can make it connect to your test environment:
rails c RAILS_ENV=test
or to your production environment:
rails c RAILS_ENV=production

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.

Strong Parameters claims param not found when it's present

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.

#users variable empty. forget to pass the collection object for will_paginate?

Problem localhost:3000/users/ won't display
I enter humbly as I am trying to make it through the rails tutorial for the first time. I am in chapter 10 and I have been trouble shooting this for 5 hours. When I attempt to visit localhost:3000/users/ I get an error (I believe this has something to do with factory_girl) that explain that the #users variable is empty and that I forgot to pass a collection object for will_paginate.
I'm currently at chapter 10, section 10.23 and each time I run:
$ bundle exec rake db:reset $ bundle exec rake db:populate
$ bundle exec rake db:test:prepare
I get an error explaining that
rake aborted!
Factory already registered: micropost
This is my second time trying this chapter as I encountered problems the first time and started from chapter 9. Please help and be clear and detailed when providing directions. I am happy to post whatever files that will be helpful.
Here is my index.html.erb - I save these as HTML, should they be saved as ruby files instead?
<% provide(:title, 'All users') %>
<h1>All users</h1>
<%= will_paginate %>
<ul class="users">
<%= render #users %>
</ul>
<%= will_paginate %>
Here is my users controller
class UsersController < ApplicationController
before_filter :signed_in_user, only: [:index, :edit, :update, :destroy]
before_filter :correct_user, only: [:edit, :update]
before_filter :admin_user, only: :destroy
def show
#user = User.find(params[:id])
#microposts = #user.microposts.paginate(page: params[:page])
end
end
def new
#user = User.new
end
def index
#title = "All users"
#users = User.paginate(:page => params[:page])
end
def create
#user = User.new(params[:user])
if #user.save
sign_in #user
flash[:success] = "Do more of the things you love!"
redirect_to #user
else
render 'new'
end
end
def edit
end
def update
if #user.update_attributes(params[:user])
flash[:success] = "Profile updated"
sign_in #user
redirect_to #user
else
render 'edit'
end
end
def destroy
User.find(params[:id]).destroy
flash[:success] = "User destroyed."
redirect_to users_url
end
private
def signed_in_user
unless signed_in?
store_location
redirect_to signin_url, notice: "Please sign in."
end
end
def correct_user
#user = User.find(params[:id])
redirect_to(root_path) unless current_user?(#user)
end
def admin_user
redirect_to(root_path) unless current_user.admin?
end
In your Users controller, make sure you have #users and if you are using will_paginate, make sure you call .paginate(page: params[:page], per_page: 20] and in your view, have <%= will_paginate #users %>.
/users should point to UsersController#index. Make sure you are assigning the collection #users.
For instance it could look like this at the most basic level:
def index
#users = User.all # not paginated
#users = User.paginate(page: params[:page]) # paginated
end
As far as the test database error, I'm guessing that's because you define a :micropost factory more than once.
Instead of #user = User.find(params[:id]) this you should use
#users = User.paginate(page: params[:page])

Resources