#project.impressionist_count - wrong number of arguments (given 2, expected 0..1) - ruby

I use rails 5
I want to count the number of views of the project
I installed gem 'impressionist'
Generate the impressions table migration
rails g impressionist
Run the migration
rake db:migrate
In view projects/show.html.erb
<%= #project.impressionist_count %>
Displayed error on line <%= #project.impressionist_count %> wrong number of arguments (given 2, expected 0..1) I am at a loss to identify the cause of the error.
Logs:
app/views/projects/show.html.erb:89:in `_app_views_projects_show_html_erb___149972252570834158_69970117978380'
Rendering /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.0.rc1/lib/action_dispatch/middleware/templates/rescues/template_error.html.erb within rescues/layout
Rendering /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.0.rc1/lib/action_dispatch/middleware/templates/rescues/_source.html.erb
Rendered /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.0.rc1/lib/action_dispatch/middleware/templates/rescues/_source.html.erb (8.9ms)
Rendering /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.0.rc1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb
Rendered /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.0.rc1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (5.1ms)
Rendering /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.0.rc1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb
Rendered /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.0.rc1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.7ms)
Rendered /usr/local/rvm/gems/ruby-2.3.0/gems/actionpack-5.0.0.rc1/lib/action_dispatch/middleware/templates/rescues/template_error.html.erb within rescues/layout (121.7ms)
DEPRECATION WARNING: #original_exception is deprecated. Use #cause instead. (called from status_code_with_paginate at /usr/local/rvm/gems/ruby-2.3.0/gems/will_paginate-3.1.0/lib/will_paginate/railtie.rb:49)
In rails console:
pry(main)> project.impressionist_count
ArgumentError: wrong number of arguments (given 2, expected 0..1)
from /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-5.0.0.rc1/lib/active_record/associations/collection_proxy.rb:731:in `count'
Model Project
class Project < ActiveRecord::Base
..........................
is_impressionable
.............................
end
ProjectsController
class ProjectsController < ApplicationController
before_action :set_project, only: [:show, :edit, :update]
before_action :authenticate_user!, only: [:new, :edit]
before_action :require_permission, only: [:edit]
before_action :set_freelancer, only: [:show]
before_action :set_response_current_user, only: :show, if: :exist_response?
after_action :verify_authorized, only: [:update]
impressionist :actions => [:show]
def show
#new_response = #project.responses.build
impressionist(#project)
end
...............................................
end

Your model should be like:
class Project < ActiveRecord::Base
..........................
include Impressionist::IsImpressionable
is_impressionable
.............................
end
In controller:
def show
#new_response = #project.responses.build
# impressionist(#project) //comment out this line
end

Related

Rails and before_action with different conditionals

I have these before_actions set in my Controller:
before_action :require_user, unless: :public?, only: [:show]
before_action :require_user, only: [:index, :edit, :update]
Basically I am trying execute the filter required_front_user in the show action only if the public? is false.
for the rest of actions I want the filter to be executed always.
Looks like the first before_action set up is ignored and totally override by the second set up.
Is it possible to combine both combinations using before_action statements or do I have to implement this logic in the filter it self?
Update
This also doesn't work:
before_action :require_user, if: :public?, only: [:index, :edit, :update]
before_action :require_user, unless: :public?, only: [:show, :index, :edit, :update]
I thought if public? returns true the first set up will be loaded, and if false the second set up will be loaded. It happens that only the second set up is loaded and if public? == true the before_action is never triggered
Update 2
This is what I found it works:
before_action :require_user_when_public, if: :public?, only: [:index, :edit, :update]
before_action :require_user_when_no_public, unless: :public?, only: [:show, :index, :edit, :update]
protected
def require_user_when_public
require_user
end
def require_user_when_no_public
require_user
end
Which is very ugly :/
before_action :require_user, only: require_user_before_actions
private
def require_user_before_actions
actions = [:index, :edit, :update]
actions << :show unless public?
actions
end
The most clean way I have found is:
before_action :require_user, only: [:index, :edit, :update]
before_action :require_user_when_no_public, unless: :public?, only: [:show]
protected
def require_user_when_no_public
require_user
end
I've only tested this a tiny bit so not super sure it'll work, but maybe something like:
before_action :require_user, if: ->(c) {
[:index, :edit, :update, !public? && :show].include?(c.action_name.to_sym)
}
As a possibly dumb / broken (that seems to work in a basic test for me as far as I can tell) alternative, possibly something like:
class <<self
alias_method :old_before_action, :before_action
end
def self.before_action(*callbacks)
options = callbacks.extract_options!
if options[:only] && options[:only].is_a?(Proc)
only_proc = options.delete(:only)
if_proc = ->(c) { Array(only_proc.(c)).reject(&:blank?).map(&:to_s).to_set.include? c.action_name }
options[:if] = Array(options[:if]).unshift(if_proc)
end
old_before_action(*callbacks, options)
end
before_action :require_user, only: ->(c) { [:index, :edit, :update, !public? && :show] }

Trying to get reviews for a specfic game

Im attempting to see reviews for a specific game that ive created. Right now my reviews/index show for all games, not just the specific game im looking for. Im assuming its just something im missing in my params but not sure...
these my are controllers...
class ReviewsController < ApplicationController
before_action :set_review, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except:[:index, :show]
before_action :correct_user, only: [:edit, :update, :destroy]
def index
#reviews = Review.all
end
def show
#review = Review.find(params[:id])
end
...
class GamesController < ApplicationController
before_action :set_game, only: [:show, :edit, :update, :destroy]
def index
#games = Game.all
end
def show
end
my routes ...
reviews#index
POST /games/:game_id/reviews(.:format) reviews#create
new_game_review GET /games/:game_id/reviews/new(.:format) reviews#new
edit_game_review GET /games/:game_id/reviews/:id/edit(.:format) reviews#edit
game_review GET /games/:game_id/reviews/:id(.:format) reviews#show
PATCH /games/:game_id/reviews/:id(.:format) reviews#update
PUT /games/:game_id/reviews/:id(.:format) reviews#update
DELETE /games/:game_id/reviews/:id(.:format) reviews#destroy
games GET /games(.:format) games#index
POST /games(.:format) games#create
new_game GET /games/new(.:format) games#new
edit_game GET /games/:id/edit(.:format) games#edit
game GET /games/:id(.:format) games#show
PATCH /games/:id(.:format) games#update
PUT /games/:id(.:format) games#update
DELETE /games/:id(.:format) games#destroy
root GET / games#index
this is how im attempting to do my link_to but its showing all the games reviews in my seeds not just a single game and all its reviews...
<%= link_to 'reviews', game_reviews_path(game_id: #game.id), #reviews %>
first RoR prj on my own, any help would be great!!
thanks!
The reason is not working is because you are not using the game_id you are passing to the ReviewsController. You need to query for Reviews belonging to the specific Game.
def index
#reviews = Review.where(game_id: params[:game_id]).all
end

Get data for belongs_to Two Parents rails 5

I have a class like the following:
class Child < ApplicationRecord
belongs_to :father
belongs_to :mother
end
My goal is to create endpoints
base-url/father/children #get all children for father
base-url/mother/children #get all children for mother
I'm wondering what the correct way of nesting these resources would be I know I can do it one way like:
class ChildrenController < ApplicationController
before action :set_father, only: %i[show]
def show
#children = #father.children.all
render json: #children
end
...
But how can I get the same for base-url/mother/children, is this possible through nested resources?
I know I can code the routes.rb to point at a specific controller function if I need to but I would like to understand if I'm missing something, i'm unsure from reading the active record and action pack docs if I am.
The Implementation I went with is as follows:
My child controller:
def index
if params[:mother_id]
#child = Mother.find_by(id: params[:mother_id]).blocks
render json: #child
elsif params[:father_id]
#child = Father.find_by(id: params[:father_id]).blocks
render json: #child
else
redirect_to 'home#index'
end
end
...
My routes.rb file:
Rails.application.routes.draw do
resources :mother, only: [:index] do
resources :child, only: [:index]
end
resources :father, only: [:index] do
resources :child, only: [:index]
end
...
base_url/mother/{mother_id}/children #get all children for mother
base_url/father/{father_id}/children #get all children for father

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

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

Resources