ActiveAdmin ForbiddenAttributesError - ruby

i am a brand new for Ruby on Rails.
I am using a ActiveAdmin and i have a problem with creating a AdminUser
ActiveModel::ForbiddenAttributesError in Admin::AdminUsersController#create
ActiveModel::ForbiddenAttributesError
Request
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"nvV++6GNTdA/nDzw1iJ6Ii84pZPcv2mzg0PK2Cg9Ag0=",
"admin_user"=>{"email"=>"admin2#example.com"},
"commit"=>"Create Admin user"}*
Rails 4.1.0
activeadmin 1.0.0
ruby 2.1
app/admin/admin_user.rb
ActiveAdmin.register AdminUser do
index do
column :email
column :current_sign_in_at
column :last_sign_in_at
column :sign_in_count
default_actions
end
form do |f|
f.inputs "Admin Details" do
f.input :email
end
f.actions
end
end
app/models/admin_user.rb
class AdminUser < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable,
:recoverable, :rememberable, :trackable, :validatable
after_create { |admin| admin.send_reset_password_instructions }
def password_required?
new_record? ? false : super
end
end
Gemfile
source 'https://rubygems.org'
gem 'rails', '4.1.0'
gem 'sqlite3'
gem 'sass-rails', '~> 4.0.3'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.0.0'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 2.0'
gem 'activeadmin', github: 'gregbell/active_admin'
gem 'polyamorous', github: 'activerecord-hackery/polyamorous'
gem 'ransack', github: 'activerecord-hackery/ransack'
gem 'formtastic', github: 'justinfrench/formtastic'
gem 'devise'
gem 'sdoc', '~> 0.4.0', group: :doc
config/environments/development.rb
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
# Sending emails works
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
end

Rails 4 uses strong parameters, which moves attribute whitelisting from the model to the controller. It is necessary to specify the attributes that you would like to be saved in the database. You have not permitted the attributes in your code, which is why you are receiving the ActiveModel::ForbiddenAttributesError.
Refer to the documentation of ActiveAdmin : Setting up Strong Parameters
You can setup strong parameters in the following way, using permit_params method which creates a method called permitted_params, use this method when overriding create or update actions:
ActiveAdmin.register AdminUser do
## ...
permit_params :attr1, :attr2 ## Add this line
end
Replace :attr1, :attr2, etc with the actual attribute names that you want to whitelist. For example: :email

What you're seeing is a security feature of newer versions of Rails. You will have to create a whitelist for the attributes which can be updated by the params as entered by the user. Otherwise, you will have to set each value manually.
Here's a sample of whitelisting certain params:
ActiveAdmin.register Post do
permit_params :title, :content, :publisher_id
end
See the ActiveAdmin docs on the subject:
https://github.com/gregbell/active_admin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters

Related

Sinatra CarrierWave Fog - NameError: uninitialized constant Fog

I have been trying to setup CarrierWave with Sinatra and Fog for S3 File Management. I constantly keep running into issues around Fog being undefined. This works fine the moment I change the storage to :file.
I have so far also tried solutions mentiohed here NameError: uninitialized constant CarrierWave::Storage::Fog and here NameError: uninitialized constant CarrierWave::Storage::Fog, heroku
But I have had no luck so far.
Here's my overall setup
Gemfile
gem 'fog', require: 'fog/aws'
gem 'carrierwave', '~> 2.0'
app.rb
require "carrierwave"
CarrierWave.configure do |config|
config.fog_credentials = {
provider: 'fog/aws', # required
aws_access_key_id: ENV['AWS_ACCESS_KEY_ID'], # required unless using use_iam_profile
aws_secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'], # required unless using use_iam_profile
use_iam_profile: true, # optional, defaults to false
region: ENV['AWS_REGION'], # optional, defaults to 'us-east-1'
}
config.fog_directory = ENV['S3_BUCKET_NAME']
config.fog_public = false # optional, defaults to true
config.fog_attributes = { cache_control: "public, max-age=#{365.days.to_i}" } # optional, defaults to {}
config.fog_provider = 'fog/aws'
end
Added this to my user class
mount_uploader :profile_picture, ProfileImageUploader
And lastly my ProfileImageUploader
class ProfileImageUploader < CarrierWave::Uploader::Base
storage :fog
end
I am still stuck at this output
NameError: uninitialized constant Fog
from ~/.rvm/gems/ruby-2.7.0/gems/carrierwave-2.1.0/lib/carrierwave/storage/fog.rb:159:in `connection'
try using
gem 'fog-aws'
and then
require 'sinatra/activerecord'
require 'carrierwave'
require 'carrierwave/orm/activerecord'
require 'fog/aws'

Image upload on rails 4 using paperclip shows broken image

Before I begin, I would like to say that I have googled and tried multiple solutions that were offered. I am still encountering the same issue.
When I upload an image using paperclip, it displays a broken image. I right clicked and inspected and found that my page is raising and error : Get http://localhost:3000/system/pins/images/000/000/008/medium/imgres.jpg 404 (Not Found).
View
<%= image_tag #pin.image.url %>
<p>
<strong>Description:</strong>
<%= #pin.description %>
</p>
<% if #pin.user == current_user %>
<%= link_to 'Edit', edit_pin_path(#pin) %>
<%= link_to 'Back', pins_path %>
<% end %>
Model
class Pin < ActiveRecord::Base
belongs_to :user
has_attached_file :image, :styles => { :medium => "300x300>", :thumb => "100x100>" }
validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/
end
Controller
class PinsController < ApplicationController
before_action :set_pin, only: [:show, :edit, :update, :destroy]
before_action :correct_user, only: [:edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]
def index
#pins = Pin.all
end
def show
end
def new
#pin = current_user.pins.build
end
def edit
end
def create
#pin = current_user.pins.build(pin_params)
if #pin.save
redirect_to #pin, notice: 'Pin was successfully created.'
else
render :new
end
end
def update
if #pin.update(pin_params)
redirect_to #pin, notice: 'Pin was successfully updated.'
else
render :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_by(id: params[:id])
redirect_to pins_path, notice: "Not authorized to edit this pin" 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, :image)
end
end
Gemfile
source 'https://rubygems.org'
ruby '2.2.6'
gem 'rails', '4.0.0'
gem 'sass-rails', '~> 4.0.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.0.0'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 1.2'
gem 'coffee-script-source', '1.8.0'
gem 'bootstrap-sass'
gem 'devise'
gem 'paperclip', '~> 4.2.0'
group :development, :test do
gem 'sqlite3'
end
group :production do
gem 'pg'
gem 'rails_12factor'
end
group :doc do
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', require: false
end
I've tried downgrading and upgrading my gem file, adding a cocaine gem, adding :path => "" and :url => "" to my model, setting the timestamp to false, restarting my computer and my server, uninstalling and reinstalling imagemagick, downloading the file.exe manually and adjusting the code to in development.rb as instructed, and changing the location of my image. I may be forgetting some things I've tried, because I've been searching on google and adjusting for hours now. Is there anyone who can help?
At a high level paperclip writes the uploaded file to a local file and stores information on the file in the database for lookup. The fact that rails is returning a 404 indicates that either 1) the file isn't being written or 2) rails isn't serving the file correctly.
The paperclip documentation on storage is pretty good as a reference: https://github.com/thoughtbot/paperclip#understanding-storage
By default rails should serve files that are in the public directory and by default paperclip stores files under public/system, so generally file serving should work in the development environment automatically.
Can you verify that the file public/system/pins/images/000/000/008/medium/imgres.jpg exists?

Rails 4, Strong Parameters, Unpermitted parameters on fields belonging to associated model

This is my first try at using models with associations with Rails 4 and for some reason I'm not able to get at the parameters POST'ed in due to a "Unpermitted parameters" error. I have tried to permit the associated fields several different ways with no success.
Basically, I have an Adoption Request with an associated Person.
class AdoptionRequest < ActiveRecord::Base
has_one :person
accepts_nested_attributes_for :person
end
and
class Person < ActiveRecord::Base
belongs_to :adoption_request
end
Here are the relevant sections from adoption_requests_controller.rb:
def create
#adoption_request = AdoptionRequest.new(adoption_request_params)
respond_to do |format|
if #adoption_request.save
format.html { redirect_to #adoption_request, notice: 'Adoption request was successfully created.' }
format.json { render action: 'show', status: :created, location: #adoption_request }
else
format.html { render action: 'new' }
format.json { render json: #adoption_request.errors, status: :unprocessable_entity }
end
end
end
private
def adoption_request_params
params.require(:adoption_request).permit(person_attributes: [:first_name, :last_name])
end
The form in the view is generated using rails-bootstrap-forms:
= bootstrap_form_for #adoption_request do |f|
= f.fields_for #adoption_request.person do |owner_fields|
= owner_fields.text_field :first_name
= owner_fields.text_field :last_name
= f.submit
Here is an example of the HTML generated by this for the first name field:
<input class="form-control" id="adoption_request_person_first_name" name="adoption_request[person][first_name]" type="text">
Now when I submit the following POST payload:
{"utf8"=>"✓", "authenticity_token"=>"kE1Q222VzXRsuLnhiO0X3mijW1TGTWSAOVgVDz/rxsE=", "adoption_request"=>{"person"=>{"first_name"=>"John", "last_name"=>"Smith"}}, "commit"=>"Create Adoption request"}
The adoption request is created, but the associated person is not. This is appears to be happening because strong parameters is not allowing the person parameters to come through. Case in point, I see this in the rails console output:
Unpermitted parameters: person
According to the strong parameters documentation, this configuration should work, but I have also tried:
params.require(:adoption_request).permit(:person, person_attributes: [:first_name, :last_name])
which results in the same error ("Unpermitted parameters: person"), and
params.require(:adoption_request).permit!
works to allow the parameters through, but this is not an acceptable solution as it negates the whole purpose of using strong parameters.
What am I doing wrong?
Here is my Gemfile, in case it is helpful:
source 'https://rubygems.org'
ruby '2.0.0'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.0.3'
# Use postgresql as the database for Active Record
gem 'pg'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 4.0.0'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.0.0'
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 1.2'
group :doc do
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', require: false
end
# Use Bootstrap
gem 'bootstrap-sass', '~> 3.3.4'
# Use Figaro to make using environment variables easier
gem 'figaro'
# Use Slim templating engine
gem "slim-rails"
# User authlogic for authentication system
gem 'authlogic'
# Use rails-bootstrap-forms to integrate rails form builder with bootstrap
gem 'bootstrap_form'
group :test do
# use MiniTest::Spec::DSL
gem 'minitest-spec-rails', '~> 4.7'
end
The app itself is more complex than this. I've simplified it to illustrate the problem.
Thanks in advance for your help!
You need to change this line
= f.fields_for #adoption_request.person do |owner_fields|
to
= f.fields_for :person do |owner_fields|
I would simply try building the Person object on save. Pass the first and last names up as hidden fields.
Otherwise I would give strong parameters a read.
if #adoption_request.save
#adoption_request.persons.build(first_name: #first_name, last_name: #last_name)

undefined method `min_cost' for ActiveModel::SecurePassword:Module

I am following Michale harlt's ruby on rails tutorial.Everything was going fine uptill I got stuck into this problem in which after giving user name and password and clicking on "Login" push button and I am getting an error "undefined method `min_cost' for ActiveModel::SecurePassword:Module".I am trying to resolve this issue from last 2 days but could'nt able to find any relevant solution.
Please help me to solve this.Thanks in advance.Here are all my relevant files of project. (I am using rails 3.2.16)
For any further information please let me know.
user.rb
class User < ActiveRecord::Base
attr_accessor :remember_token
before_save { self.email = email.downcase }
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
has_secure_password
validates :password, length: { minimum: 6 }
# Returns the hash digest of the given string.
def User.digest(string)
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
BCrypt::Engine.cost
BCrypt::Password.create(string, cost: cost)
end
# Returns a random token.
def User.new_token
SecureRandom.urlsafe_base64
end
# Remembers a user in the database for use in persistent sessions.
def remember
self.remember_token = User.new_token
update_attribute(:remember_digest, User.digest(remember_token))
end
# Returns true if the given token matches the digest.
def authenticated?(remember_token)
BCrypt::Password.new(remember_digest).is_password?(remember_token)
end
end
sessions_helper.rb
module SessionsHelper
# Logs in the given user.
def log_in(user)
session[:user_id] = user.id
end
# Remembers a user in a persistent session.
def remember(user)
user.remember
cookies.permanent.signed[:user_id] = user.id
cookies.permanent[:remember_token] = user.remember_token
end
# Returns the user corresponding to the remember token cookie.
def current_user
if (user_id = session[:user_id])
#current_user ||= User.find_by_id(user_id)
elsif (user_id = cookies.signed[:user_id])
user = User.find_by_id(user_id)
if user && user.authenticated?(cookies[:remember_token])
log_in user
#current_user = user
end
end
end
# Returns true if the user is logged in, false otherwise.
def logged_in?
!current_user.nil?
end
# Log Out Current User
def log_out
session.delete(:user_id)
#current_user = nil
end
end
sessions_controller.rb
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by_email(params[:session][:email].downcase)
if user && user.authenticate(params[:session][:password])
log_in user
remember user
redirect_to user
else
flash.now[:danger] = 'Invalid email/password combination'
render 'new'
end
end
def destroy
log_out
redirect_to home_path
end
end
GemFile
source 'https://rubygems.org'
gem 'rails', '3.2.16'
gem 'bcrypt-ruby', '~> 3.1.2'
gem 'strong_parameters'
# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'
group :development, :test do
gem 'sqlite3', '1.3.9'
gem 'guard'
end
group :test do
gem 'minitest-reporters'
gem 'mini_backtrace', '0.1.3'
gem 'guard-minitest', '2.3.1'
end
group :production do
gem 'pg', '0.17.1'
gem 'rails_12factor', '0.0.2'
gem 'puma', '2.11.1'
end
# Gems used only for assets and not required
# in production environments by default.
group :assets do
gem 'coffee-rails', '~> 3.2.1'
gem 'sass-rails', '>= 3.2'
gem 'bootstrap-sass', '~> 3.3.4'
gem 'sprockets-rails', '=2.0.0.backport1'
gem 'sprockets', github: 'tessi/sprockets', branch: '2_2_2_backport2'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', :platforms => :ruby
gem 'uglifier', '>= 1.0.3'
end
gem 'jquery-rails'
# To use ActiveModel has_secure_password
# gem 'bcrypt-ruby', '~> 3.0.0'
# To use Jbuilder templates for JSON
# gem 'jbuilder'
# Use unicorn as the app server
# gem 'unicorn'
# Deploy with Capistrano
# gem 'capistrano'
# To use debugger
# gem 'debugger'
Application Trace
app/models/user.rb:14:in `digest'
app/models/user.rb:27:in `remember'
app/helpers/sessions_helper.rb:10:in `remember'
app/controllers/sessions_controller.rb:10:in `create'
As far as I remember, SecurePassword#min_cost appeared in rails4 (or in rails3 > 3.2.16.)
Since you are just learning, my advice would be not to concentrate on solving this particular error, but just substitute the problematic line with:
cost = BCrypt::Engine::MIN_COST
or even with
cost = 10
and go further. Whether you are still to fix this, you should upgrade your rails up to 4 (or whatever version this method was introduced.)

Cannot get my Articles controller to create a blog Article with a picture. I am using imagemagick and carrierwave

My create action in ArticlesController seems fine if I create an Article without uploading a picture. However, if I try to upload a picture for an article, I get the error:
ActionController::UrlGenerationError in ArticlesController#create
No route matches {:action=>"show", :controller=>"articles", :id=>nil} missing required keys: [:id]
Here is my Articles controller:
class ArticlesController < ApplicationController
before_filter :require_login, only: [:new, :create, :edit, :update, :destroy]
def index
#articles = Article.all
end
def show
#article = Article.find(params[:id])
#comment = Comment.new
#comment.article_id = #article.id
end
def new
#article = Article.new
end
def create
#article = Article.new(article_params)
#article.save
redirect_to article_path(#article)
end
def edit
#article = Article.find(params[:id])
end
def destroy
#article = Article.find(params[:id])
#article.destroy
redirect_to articles_path
end
def update
#article = Article.find(params[:id])
#article.update(article_params)
flash.notice = "Article '#{#article.title}' Updated!"
redirect_to article_path(#article)
end
private
def article_params
params.require(:article).permit(:title, :body, :tag_list, :picture)
end
end
Here is my Article model:
class Article < ActiveRecord::Base
has_many :comments
has_many :taggings
has_many :tags, through: :taggings
mount_uploader :picture, PictureUploader
validate :picture_size
def tag_list
self.tags.collect do |tag|
tag.name
end.join(", ")
end
def tag_list=(tags_string)
tag_names = tags_string.split(",").collect{|s| s.strip.downcase}.uniq
new_or_found_tags = tag_names.collect { |name| Tag.find_or_create_by(name: name) }
self.tags = new_or_found_tags
end
# Validates the size of an uploaded picture.
def picture_size
if picture.size > 5.megabytes
errors.add(:picture, "should be less than 5MB")
end
end
end
My Gemfile :
source 'http://rubygems.org'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.1.8'
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 4.0.3'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.0.0'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
gem 'carrierwave', '0.10.0'
gem 'mini_magick', '~> 4.0.4'
gem 'fog', '~> 1.27.0'
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.0'
gem 'sorcery'
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', '~> 0.4.0', group: :doc
# Use ActiveModel has_secure_password
gem 'bcrypt', '~> 3.1.7'
# Use unicorn as the app server
# gem 'unicorn'
# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
# Use debugger
# gem 'debugger', group: [:development, :test]
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin]
And finally my picture uploader:
# encoding: utf-8
class PictureUploader < CarrierWave::Uploader::Base
# Include RMagick or MiniMagick support:
# include CarrierWave::RMagick
include CarrierWave::MiniMagick
process resize_to_limit: [500, 500]
if Rails.env.production?
storage :fog
else
storage :file
end
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
# Provide a default URL as a default if there hasn't been a file uploaded:
# def default_url
# # For Rails 3.1+ asset pipeline compatibility:
# # ActionController::Base.helpers.asset_path("fallback/" + [version_name, "default.png"].compact.join('_'))
#
# "/images/fallback/" + [version_name, "default.png"].compact.join('_')
# end
# Process files as they are uploaded:
# process :scale => [200, 300]
#
# def scale(width, height)
# # do something
# end
# Create different versions of your uploaded files:
# version :thumb do
# process :resize_to_fit => [50, 50]
# end
# Add a white list of extensions which are allowed to be uploaded.
# For images you might use something like this:
def extension_white_list
%w(jpg jpeg gif png)
end
# Override the filename of the uploaded files:
# Avoid using model.id or version_name here, see uploader/store.rb for details.
# def filename
# "something.jpg" if original_filename
# end
end
What am I doing wrong with carrierwave and Imagemagic to get
this error ?

Resources