undefined method `[]' for nil:NilClass but the article is published - ruby-on-rails

I have created a form in order to create articles, it has fields for title, date, content, main image, and a special field for the multiple upload. Images are uploaded with Carrierwave.
I have two differents models and controllers that work with this form. progress and progress_attachments.
As I want to attach multiple images in order to create a photos gallery I have created this other controller progress_attachment I followed SSR explanations
When I submit my form, I have this error
NoMethodError in ProgressesController#create
undefined method `[]' for nil:NilClass
Even though the article is published... (I can find it in rails console, and If I go back to the show)
I beleive that this undefined method []comes from my create method in the the progress controller, but I am missing something and I don't understand what...??
progresses_controller.rb
class ProgressesController < ApplicationController
def index
#progresses = Progress.all
end
def show
#progress = Progress.find(params[:id])
#progress_attachments = #progress.progress_attachments.all
end
def new
#progress = Progress.new
#progress_attachment = #progress.progress_attachments.build
end
def create
#progress = Progress.new(progress_params)
respond_to do |format|
if #progress.save
params[:progress_attachments]['image'].each do |a|
#progress_attachment = #progress.progress_attachments.create!(:image => a)
end
format.html { redirect_to progresses_path, notice: 'Progress was successfully created.' }
else
format.html { render action: 'new' }
end
end
end
def update
respond_to do |format|
if #progress.update(article_params)
format.html { redirect_to #progress, notice: 'Article was successfully updated.' }
format.json { render :show, status: :ok, location: #progress }
else
format.html { render :edit }
format.json { render json: #progress.errors, status: :unprocessable_entity }
end
end
end
def destroy
#progress.destroy
respond_to do |format|
format.html { redirect_to articles_url, notice: 'Article was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def progress_params
params.require(:progress).permit(:title, :content, :date, :main_image, progress_attachments_attributes: [:id, :progress_id, :image])
end
end
progress_attachments_controller.rb
class ProgressAttachmentsController < ApplicationController
before_action :set_progress_attachment, only: [:show, :edit, :update, :destroy]
def index
#progress_attachments = ProgressAttachment.all
end
def new
#progress_attachment = ProgressAttachment.new
end
def create
#progress_attachment = ProgressAttachment.new(progress_attachment_params)
#progress_attachment = #progress.progress_attachments.build
respond_to do |format|
if #progress_attachment.save
format.html { redirect_to #progress_attachment, notice: 'Progress attachment was successfully created.' }
format.json { render :show, status: :created, location: #progress_attachment }
else
format.html { render :new }
format.json { render json: #progress_attachment.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #progress_attachment.update(progress_attachment_params)
format.html { redirect_to #progress_attachment, notice: 'Progress attachment was successfully updated.' }
format.json { render :show, status: :ok, location: #progress_attachment }
else
format.html { render :edit }
format.json { render json: #progress_attachment.errors, status: :unprocessable_entity }
end
end
end
def destroy
#progress_attachment.destroy
respond_to do |format|
format.html { redirect_to progress_attachments_url, notice: 'Progress attachment was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def set_progress_attachment
#progress_attachment = ProgressAttachment.find(params[:id])
end
def progress_attachment_params
params.require(:progress_attachment).permit(:progress_id, :image)
end
end
the form in views/progresses/new.html.slim
= simple_form_for(#progress, html: { multipart: true} ) do |f|
=f.input :title
=f.input :date
=f.input :content
=f.input :main_image
=f.simple_fields_for :progress_attachments do |f|
=f.input_field :image, multiple: true, name: "progress_attachments_attributes[:image][]"
=f.button :submit
I have edited the form since I have solved the problem of multiple uploads
models/progress_attachment.rb
class ProgressAttachment < ActiveRecord::Base
mount_uploader :image, ImageUploader
belongs_to :progress
validates :image, presence: true
end
models/progress.rb
class Progress < ActiveRecord::Base
default_scope ->{order(created_at: :DESC)}
mount_uploader :main_image, MainImageUploader
has_many :progress_attachments
accepts_nested_attributes_for :progress_attachments
validates :main_image, presence: true
validates :title, presence: true
validates :content, presence: true
validates :date, presence: true
end
EDIT
this is my pry on my actual controller.
Started POST "/progresses" for ::1 at 2016-09-02 01:37:49 +0200
ActiveRecord::SchemaMigration Load (0.1ms) SELECT "schema_migrations".* FROM "schema_migrations"
Processing by ProgressesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"KdZkIvo+lbmE8JPlMNOOFc2grNG6w9u4kuO3kII2erOG+iD3RXfqutdwzAxvMIQbVGAzHVGawcBMW+WJfgZ+uA==", "progress"=>{"title"=>"Hello", "date"=>"1st september 2016", "content"=>"bonjourbonjour", "main_image"=>#<ActionDispatch::Http::UploadedFile:0x007fede250ecb8 #tempfile=#<Tempfile:/var/folders/11/mdddnw8d0zd961bsfkq1cjy00000gn/T/RackMultipart20160902-22001-1l0mkug.jpg>, #original_filename="12915103_10208497250246588_1486835977_o.jpg", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"progress[main_image]\"; filename=\"12915103_10208497250246588_1486835977_o.jpg\"\r\nContent-Type: image/jpeg\r\n">, "progress_attachments_attributes"=>{"0"=>{"image"=>#<ActionDispatch::Http::UploadedFile:0x007fede250eb78 #tempfile=#<Tempfile:/var/folders/11/mdddnw8d0zd961bsfkq1cjy00000gn/T/RackMultipart20160902-22001-9k74to.jpg>, #original_filename="band.jpg", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"progress[progress_attachments_attributes][0][image]\"; filename=\"band.jpg\"\r\nContent-Type: image/jpeg\r\n">}}}, "commit"=>"Create Progress"}
From: /Users/nelly/Desktop/ROR/leschner_guitars/app/controllers/progresses_controller.rb # line 20 ProgressesController#create:
19: def create
=> 20: binding.pry
21: #progress = Progress.new(progress_params)
22:
23: respond_to do |format|
24: if #progress.save
25: params[:progress_attachments]['image'].each do |a|
26: #progress_attachment = #progress.progress_attachments.create!(:image => a)
27: end
28:
29: format.html { redirect_to progresses_path, notice: 'Progress was successfully created.' }
30: else
31: format.html { render action: 'new' }
32: end
33: end
34: end
[1] pry(#<ProgressesController>)> params
=> {"utf8"=>"✓",
"authenticity_token"=>"KdZkIvo+lbmE8JPlMNOOFc2grNG6w9u4kuO3kII2erOG+iD3RXfqutdwzAxvMIQbVGAzHVGawcBMW+WJfgZ+uA==",
"progress"=>
{"title"=>"Hello",
"date"=>"1st september 2016",
"content"=>"bonjourbonjour",
"main_image"=>
#<ActionDispatch::Http::UploadedFile:0x007fede250ecb8
#content_type="image/jpeg",
#headers=
"Content-Disposition: form-data; name=\"progress[main_image]\"; filename=\"12915103_10208497250246588_1486835977_o.jpg\"\r\nContent-Type: image/jpeg\r\n",
#original_filename="12915103_10208497250246588_1486835977_o.jpg",
#tempfile=#<File:/var/folders/11/mdddnw8d0zd961bsfkq1cjy00000gn/T/RackMultipart20160902-22001-1l0mkug.jpg>>,
"progress_attachments_attributes"=>
{"0"=>
{"image"=>
#<ActionDispatch::Http::UploadedFile:0x007fede250eb78
#content_type="image/jpeg",
#headers=
"Content-Disposition: form-data; name=\"progress[progress_attachments_attributes][0][image]\"; filename=\"band.jpg\"\r\nContent-Type: image/jpeg\r\n",
#original_filename="band.jpg",
#tempfile=#<File:/var/folders/11/mdddnw8d0zd961bsfkq1cjy00000gn/T/RackMultipart20160902-22001-9k74to.jpg>>}}},
"commit"=>"Create Progress",
"controller"=>"progresses",
"action"=>"create"}
[2] pry(#<ProgressesController>)>
and with changing like SteveTurczyn suggested:
Started POST "/progresses" for ::1 at 2016-09-02 01:49:14 +0200
Processing by ProgressesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"XevIqKvA6UhcmipGb/zu8wJ3ItCwA5EBjldLQhwyXj7yx4x9FImWSw8ada8wH+T9m7e9HFtai3lQ7xlb4AJaNQ==", "progress"=>{"title"=>"This is a title", "date"=>"Today !", "content"=>"That's a short content", "main_image"=>#<ActionDispatch::Http::UploadedFile:0x007fb00af89dc0 #tempfile=#<Tempfile:/var/folders/11/mdddnw8d0zd961bsfkq1cjy00000gn/T/RackMultipart20160902-22410-13jb3ww.jpg>, #original_filename="band.jpg", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"progress[main_image]\"; filename=\"band.jpg\"\r\nContent-Type: image/jpeg\r\n">, "progress_attachments_attributes"=>{"0"=>{"image"=>#<ActionDispatch::Http::UploadedFile:0x007fb00af89c80 #tempfile=#<Tempfile:/var/folders/11/mdddnw8d0zd961bsfkq1cjy00000gn/T/RackMultipart20160902-22410-6mze6c.jpg>, #original_filename="boss2.jpg", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"progress[progress_attachments_attributes][0][image]\"; filename=\"boss2.jpg\"\r\nContent-Type: image/jpeg\r\n">}}}, "commit"=>"Create Progress"}
From: /Users/nelly/Desktop/ROR/leschner_guitars/app/controllers/progresses_controller.rb # line 20 ProgressesController#create:
19: def create
=> 20: binding.pry
21: #progress = Progress.new(progress_params)
22:
23: respond_to do |format|
24: if params[:progress_attachments]
25: params[:progress_attachments]['image'].each do |a|
26: #progress_attachment = #progress.progress_attachments.create!(:image => a)
27: end
28: format.html { redirect_to progresses_path, notice: 'Progress was successfully created.' }
29: else
30: format.html { render action: 'new' }
31: end
32: end
33: end
[1] pry(#<ProgressesController>)> params
=> {"utf8"=>"✓",
"authenticity_token"=>"XevIqKvA6UhcmipGb/zu8wJ3ItCwA5EBjldLQhwyXj7yx4x9FImWSw8ada8wH+T9m7e9HFtai3lQ7xlb4AJaNQ==",
"progress"=>
{"title"=>"This is a title",
"date"=>"Today !",
"content"=>"That's a short content",
"main_image"=>
#<ActionDispatch::Http::UploadedFile:0x007fb00af89dc0
#content_type="image/jpeg",
#headers="Content-Disposition: form-data; name=\"progress[main_image]\"; filename=\"band.jpg\"\r\nContent-Type: image/jpeg\r\n",
#original_filename="band.jpg",
#tempfile=#<File:/var/folders/11/mdddnw8d0zd961bsfkq1cjy00000gn/T/RackMultipart20160902-22410-13jb3ww.jpg>>,
"progress_attachments_attributes"=>
{"0"=>
{"image"=>
#<ActionDispatch::Http::UploadedFile:0x007fb00af89c80
#content_type="image/jpeg",
#headers="Content-Disposition: form-data; name=\"progress[progress_attachments_attributes][0][image]\"; filename=\"boss2.jpg\"\r\nContent-Type: image/jpeg\r\n",
#original_filename="boss2.jpg",
#tempfile=#<File:/var/folders/11/mdddnw8d0zd961bsfkq1cjy00000gn/T/RackMultipart20160902-22410-6mze6c.jpg>>}}},
"commit"=>"Create Progress",
"controller"=>"progresses",
"action"=>"create"}
Thanks for your help

unless params[:progress_attachments].nil?
params[:progress_attachments]['image'].each do |a|
#progress_attachment = #progress.progress_attachments.create!(:image => a)
end
end

This is a likely source of your error...
params[:progress_attachments]['image'].each do |a|
If your params don't have a :progress_attachments key it will return nil, and doing nil['image'] will give you exactly the error you're seeing.
You may want to inspect the params coming into the create method using byebug or pry. If it's legitimate that no progress attachment needs to be present then you can wrap the each loop in if params[:progess_attachments] ... end
if params[:progress_attachments]
params[:progress_attachments]['image'].each do |a|
#progress_attachment = #progress.progress_attachments.create!(:image => a)
end
end
I'm not actually clear that this will be the finished solution as I'm not clear you'll have an array of images but inspection of the params should clarify that.

Related

Rails 5 - Strong Parameters for Nested Attributes

I am having trouble structuring my nested attributes for my model Request.
The data is being passed in the correct way from my POST action.
What am I missing to whitelist these parameters?
Appreciate any help.
Console Output
Started POST "/requests" for 127.0.0.1 at 2017-06-08 10:57:15 -0400
Processing by RequestsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"fmvhoPxVpcHoqOd32mO/HJMrfaPUd+KbNqDJiSRs78U44Y0uL3prpTfU6wmw7PAwv0b+mRHXOGMLvD9bsZpxnw==", "request"=>{"concierge_name"=>"Alex", "concierge_number"=>"954-123-4567", "concierge_email"=>"alex#email.com", "client_name"=>"Adam", "client_number"=>"954-765-4321", "client_email"=>"adam#email.com", "hotel_employee"=>"0", "concierge_service"=>"0", "vip_promoter"=>"0", "arriving_with_client"=>"1", "client_alone"=>"0", "males"=>"", "females"=>"1", "table_minimum"=>"1000", "arrival_time(1i)"=>"2017", "arrival_time(2i)"=>"6", "arrival_time(3i)"=>"8", "arrival_time(4i)"=>"14", "arrival_time(5i)"=>"56", "table_location_ids"=>["1"], "drink_attributes"=>[{"id"=>"1", "quantity"=>"1"}, {"id"=>"2", "quantity"=>""}, {"id"=>"3", "quantity"=>""}, {"id"=>"4", "quantity"=>""}], "chaser_ids"=>["1"], "comments"=>""}, "commit"=>"Submit"}
Completed 500 Internal Server Error in 8ms (ActiveRecord: 0.0ms)
ActiveModel::UnknownAttributeError (unknown attribute 'drink_attributes' for Request.):
app/models/request.rb
class Request < ApplicationRecord
has_many :request_drinks
has_many :drinks, through: :request_drinks
accepts_nested_attributes_for :drinks
end
app/model/drink.rb
class Drink < ApplicationRecord
has_many :request_drinks
has_many :requests, through: :request_drinks
end
app/model/request_drink.rb
class RequestDrink < ApplicationRecord
belongs_to :request
belongs_to :drink
end
app/controllers/request_controller.rb
class RequestsController < ApplicationController
before_action :set_request, only: [:show,
:edit,
:update,
:destroy]
def index
#requests = Request.search(params[:term], params[:filter], params[:page])
end
def show
end
def new
#request = Request.new
#drinks = Drink.active
end
def edit
end
def create
#request = Request.new(request_params)
respond_to do |format|
if #request.save
format.html { redirect_to thanks_path, notice: 'Request was successfully created.' }
format.json { render :show, status: :created, location: #request }
else
format.html { render :new }
format.json { render json: #request.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #request.update(request_params)
format.html { redirect_to #request, notice: 'Request was successfully updated.' }
format.json { render :show, status: :ok, location: #request }
else
format.html { render :edit }
format.json { render json: #request.errors, status: :unprocessable_entity }
end
end
end
def destroy
#request.destroy
respond_to do |format|
format.html { redirect_to requests_url, notice: 'Request was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def set_request
#request = Request.find(params[:id])
end
def request_params
params.require(:request).permit(:concierge_name,
:concierge_number,
:concierge_email,
:client_name,
:client_number,
:client_email,
:hotel_employee,
:concierge_service,
:vip_promoter,
:arriving_with_client,
:client_alone,
:people,
:males,
:females,
:table_minimum,
:arrival_time,
:comments,
:drink_attributes => [:id, :quantity]
)
end
end
app/views/requests/_form.html.erb
...
<div class="field-3">
<h4>Drinks</h4>
<% #drinks.all.each do |d| %>
<%= hidden_field_tag "request[drink_attributes][][id]", d.id %>
<%= number_field_tag "request[drink_attributes][][quantity]" %>
<%= d.name %>
<br />
<% end %>
</div>
...
You need to use the plural form of the object (i.e. drinks) when using nested attributes.
So, in your request_params change:
:drink_attributes => [:id, :quantity]
to:
:drinks_attributes => [:id, :quantity]
An you need to update your form too:
...
<%= hidden_field_tag "request[drinks_attributes][][id]", d.id %>
<%= number_field_tag "request[drinks_attributes][][quantity]" %>
...

What to do with error 'Please review the problems below:' using cocoon gem?

I am creating an ruby on rails 5 application. It is a todolist kind of application and using simple_form, haml-rails and cocoon gem. This is a application with nested form.
Generated a scaffold for goal and created model for action
Goal.rb and Action.rb
class Goal < ApplicationRecord
has_many :actions
accepts_nested_attributes_for :actions, reject_if: :all_blank
end
class Action < ApplicationRecord
belongs_to :goal
end
Then added the actions_attribute to permit in the params
class GoalsController < ApplicationController before_action :set_goal, only: [:show, :edit, :update, :destroy] def index
#goals = Goal.all end def show end def new
#goal = Goal.new end def edit end def create
#goal = Goal.new(goal_params)
respond_to do |format|
if #goal.save
format.html { redirect_to #goal, notice: 'Goal was successfully created.' }
format.json { render :show, status: :created, location: #goal }
else
format.html { render :new }
format.json { render json: #goal.errors, status: :unprocessable_entity }
end
end end def update
respond_to do |format|
if #goal.update(goal_params)
format.html { redirect_to #goal, notice: 'Goal was successfully updated.' }
format.json { render :show, status: :ok, location: #goal }
else
format.html { render :edit }
format.json { render json: #goal.errors, status: :unprocessable_entity }
end
end end def destroy
#goal.destroy
respond_to do |format|
format.html { redirect_to goals_url, notice: 'Goal was successfully destroyed.' }
format.json { head :no_content }
end end private
def set_goal
#goal = Goal.find(params[:id])
end
def goal_params
params.require(:goal).permit(:name, :purpose, :deadline, actions_attributes: [:step])
end
end
Forms for both form.html and action.html
_form.html.haml
= simple_form_for(#goal) do |f|
= f.error_notification
.form-inputs
= f.input :name
= f.input :purpose
= f.input :deadline
%h3 Actions
#tasks
= f.simple_fields_for :actions do |action|
= render 'action_fields', f: action
.links
= link_to_add_association 'Add', f, :actions
.form-actions
= f.button :submit
// action.html.haml
.nested-fields
= f.input :step
= f.input :done, as: :boolean
= link_to_remove_association "remove task", f
log in the console when i submit form
Processing by GoalsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"jel0g+oCkNaspe7T9dz7suDczIOdoKJqPqPDK9ta0WLPbwaSPBwshrDD2BrNAFeLoDx+0/soe11MWaZaH8cQoA==", "goal"=>{"name"=>"ja", "purpose"=>"asdfd", "deadline"=>"asdfasd", "actions_attributes"=>{"0"=>{"step"=>"ARasd", "done"=>"1", "_destroy"=>"false"}, "1475080334356"=>{"step"=>"", "done"=>"0", "_destroy"=>"false"}}}, "commit"=>"Create Goal"}
Unpermitted parameter: _destroy
Unpermitted parameter: _destroy
(0.5ms) BEGIN
(0.5ms) ROLLBACK
Rendering goals/new.html.haml within layouts/application
Rendered goals/_action_fields.html.haml (18.5ms)
Rendered goals/_action_fields.html.haml (26.5ms)
Rendered goals/_action_fields.html.haml (19.0ms)
Rendered goals/_form.html.haml (252.5ms)
Rendered goals/new.html.haml within layouts/application (309.0ms)
Completed 200 OK in 932ms (Views: 898.5ms | ActiveRecord: 1.0ms)
The console log shows: Unpermitted parameter: done
This is because in your controller, only these parameters are permitted:
params.require(:goal).permit(:name, :purpose, :deadline, actions_attributes: [:step])

rails object expected got string in association

I have this:
<%= f.association :gestor, selected: current_usuario.gestor_id, label_method: :descricao, value: current_usuario.gestor_id, disabled: true %>
My controller:
def create
#usuario = Usuario.new(usuario_params)
respond_to do |format|
if #usuario.save
format.html { redirect_to controle_usuarios_path, notice: 'Usuario was successfully updated.' }
format.json { render :index, status: :ok, location: #usuario }
else
format.html { render :new }
end
end
end
(...)
def usuario_params
params.require(:usuario).permit(:cpf, :usuario_pai, :gestor_id, :email, :password, :password_confirmation, :agente_id, :perfil_id)
end
And console:
Processing by ControleUsuariosController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"xnMQOvRLO3cCrq/l5KSSG0qB3Pc8S4wtSgs4PTCTkaJ5kLLwMD73s/4TeBWYYbvmBKzvBca4T0eMT9F9UQo/Ew==", "usuario"=>{"usuario_pai"=>"admin#mail.com", "agente_id"=>"2", "cpf"=>"111.111.111-11", "email"=>"xxx#xxx.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "perfil_id"=>"2"}, "commit"=>"Criar Usuario"}
The params gestor_id don't come, why? The error is this:
Usuario(#70271925151780) expected, got String(#3432540)
Rails is looking for gester_id and you are passing in gester as the param so it is being removed. Try changing it in your view to gester_id or in your params filter to gester.

Updated ruby and rails gives error to .new .update methods

I have recently updated my ruby version and rails version.
ruby 1.9.3 to ruby 2.1.1
rails 3.2.6 to rails 4.0.0
Then installed following new gems
protected_attributes(1.0.3)
turbolinks(2.5.3)
While running code i got following error to create and update method.
Got wrong number of arguments (2 for 1) error at .new, .update mehods.
eg.
**wrong number of arguments (2 for 1)**
def create
**#gallery = Gallery.new(gallery_params)**
respond_to do |format|
if #gallery.save
format.html { redirect_to :back, :notice => t('notice.gallery_created') }
format.json { render json: #gallery, status: :created, location: #gallery }
else
format.html { render action: "new" }
format.json { render json: #gallery.errors, status: :unprocessable_entity }
end
end
end
private
def gallery_params
params.require(:gallery).permit(:title, :user_id, :description, images_attributes: [:title, :description, :image, :user_id])
end
I am sending following parameters from my form.
Parameters: {"utf8"=>"✓", "authenticity_token"=>"4DosQk69bQzV9idZapxjseVPNedORytYtNYH4rUCeBk=", "gallery"=>{"title"=>"test title 10", "description"=>"this is the gallery desription", "user_id"=>"1", "images_attributes"=>{"0"=>{"title"=>"test image", "description"=>"", "image"=>#<ActionDispatch::Http::UploadedFile:0xb48788b8 #tempfile=#<Tempfile:/tmp/RackMultipart20160229-7649-3kw561>, #original_filename="564650_685411374823853_181629729_n.jpg", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"gallery[images_attributes][0][image]\"; filename=\"564650_685411374823853_181629729_n.jpg\"\r\nContent-Type: image/jpeg\r\n">, "user_id"=>"1"}}}, "commit"=>"Update", "locale"=>"en"}
It gives me error to every form (form_for or nested_form_for) in my application.
Tried following code in controller which saves my data but .new .update still have issue.
eg.
#gallery = Gallery.new
#gallery.title = "test title 10"
#gallery.description = "this is the gallery description"
#gallery.user_id = 1
#gallery.save
Try this:
def gallery_params
params.require(:gallery).permit(:title, :user_id, :description, images_attributes: [:title, :description, :image, :user_id])
end
Once try like this and let us see if the issue is in strong parameters
def create
#gallery = Gallery.new({"title"=>"test title 10", "description"=>"this is the gallery desription", "user_id"=>"1", "images_attributes"=>{"0"=>{"title"=>"test image", "description"=>"", "image"=>#<ActionDispatch::Http::UploadedFile:0xb48788b8 #tempfile=#<Tempfile:/tmp/RackMultipart20160229-7649-3kw561>, #original_filename="564650_685411374823853_181629729_n.jpg", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"gallery[images_attributes][0][image]\"; filename=\"564650_685411374823853_181629729_n.jpg\"\r\nContent-Type: image/jpeg\r\n">, "user_id"=>"1"}}})
respond_to do |format|
if #gallery.save
format.html { redirect_to :back, :notice => t('notice.gallery_created') }
format.json { render json: #gallery, status: :created, location: #gallery }
else
format.html { render action: "new" }
format.json { render json: #gallery.errors, status: :unprocessable_entity }
end
end
end

Forbidden Attributes Error when Creating

I'm on Rails 4 and Ruby 2 and am trying to fix a bug that is giving me a Forbidden Attributes error when I'm creating a new record.
Here is my Create code in my controller:
def create
#instructor = Instructor.new(instructor_params)
respond_to do |format|
if #instructor.save
format.html { redirect_to #instructor, notice: 'Instructor was successfully created.' }
format.json { render json: #instructor, status: :created, location: #instructor }
else
format.html { render action: "new" }
format.json { render json: #instructor.errors, status: :unprocessable_entity }
end
end
end
And my strong parameters code:
def instructor_params
params.require(:instructor).permit(:bio, :hometown, :name, :school, :sort_order, :started_sailing, :started_teaching, :photo)
end
Here is my instructor.rb file:
class Instructor < ActiveRecord::Base
validates_presence_of :bio, :name
mount_uploader :photo, PhotoUploader
def experience
distance_of_time_in_words_to_now (self.started_sailing)
end
end
The error I'm getting is:
ActiveModel::ForbiddenAttributesError in InstructorsController#create
ActiveModel::ForbiddenAttributesError
Rails.root: /Users/scottsipiora/Sites/clycss
Application Trace | Framework Trace | Full Trace
Request
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"l2159VRjW9dUluWPJBxsubEt7t37CztXXVX/kjEpGfs=",
"instructor"=>{"name"=>"Libby",
"bio"=>"Bio content",
"sort_order"=>"",
"photo"=>#<ActionDispatch::Http::UploadedFile:0x007fd6aad96ec0 #tempfile=#<Tempfile:/var/folders/3k/fnl40lzs2v55jvj8yj6y07gh0000gn/T/RackMultipart20140706-8616-1mzzdxw>,
#original_filename="Libby2.jpg",
#content_type="image/jpeg",
#headers="Content-Disposition: form-data; name=\"instructor[photo]\"; filename=\"Libby2.jpg\"\r\nContent-Type: image/jpeg\r\n">},
"commit"=>"Create Instructor"}
I'm using cancan for authorization and found this page:
https://github.com/ryanb/cancan/issues/835
I tried the workaround posted by AntonTrapp shown below, but that didn't work either.
before_filter do
resource = controller_name.singularize.to_sym
method = "#{resource}_params"
params[resource] &&= send(method) if respond_to?(method, true)
end
Any idea what I'm doing wrong? I'm stumped.
Thanks in advance.

Resources