I am trying to create some sort of a nested file upload. I have Images and Albums, which are related through the model AlbumImages. Images can be part of an album. The upload is carried out through Carrierwave.
I want to be able to upload Images in two ways:
directly through Images
through Albums
When uploading Images through Albums they should be uploaded and inserted into the Images and AlbumImages tables.
I can upload single images through Images, but to my surprise, my current implementation for uploading multiple images through Albums results in 2 separate data entries. (This used to work under Rails 3) The first entry is empty and the second is the one I am aiming for.
Started PATCH "/admin/albums/38" for ::1 at 2022-05-20 11:18:44 +0200
Processing by Admin::AlbumsController#update as HTML
Parameters: {"authenticity_token"=>"[FILTERED]", "album"=>{"images_attributes"=>[{"file_name"=>""}, {"file_name"=>#<ActionDispatch::Http::UploadedFile:0x00007f8f75185c70 #tempfile=#<Tempfile:/var/folders/yg/pfjwzpkx5wq9d27svk760h0h0000gn/T/RackMultipart20220520-19476-kto7za.jpg>, #original_filename="some-image.jpg", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"album[images_attributes][][file_name]\"; filename=\"some-image.jpg\"\r\nContent-Type: image/jpeg\r\n">, "author"=>"Some Author", "copyright"=>"Someone", "funds_ids"=>["1", "6"]}]}, "commit"=>"Save", "id"=>"38"}
Admin Load (0.3ms) SELECT `admins`.* FROM `admins` WHERE `admins`.`id` = 1 ORDER BY `admins`.`id` ASC LIMIT 1
Album Load (0.2ms) SELECT `albums`.* FROM `albums` WHERE `albums`.`id` = 38 LIMIT 1
↳ app/controllers/admin/albums_controller.rb:39:in `update'
TRANSACTION (0.2ms) BEGIN
↳ app/controllers/admin/albums_controller.rb:40:in `update'
Fund Load (0.5ms) SELECT `funds`.* FROM `funds` WHERE `funds`.`id` IN (1, 6)
↳ app/controllers/admin/albums_controller.rb:40:in `update'
Section Load (0.3ms) SELECT `sections`.* FROM `sections` WHERE `sections`.`id` = 5 LIMIT 1
↳ app/controllers/admin/albums_controller.rb:40:in `update'
Fund Exists? (0.3ms) SELECT 1 AS one FROM `funds` WHERE `funds`.`name` = 'SomeFundA' AND `funds`.`id` != 1 LIMIT 1
↳ app/controllers/admin/albums_controller.rb:40:in `update'
Fund Exists? (0.2ms) SELECT 1 AS one FROM `funds` WHERE `funds`.`name` = 'SomeFundB' AND `funds`.`id` != 6 LIMIT 1
↳ app/controllers/admin/albums_controller.rb:40:in `update'
Album Exists? (0.2ms) SELECT 1 AS one FROM `albums` WHERE `albums`.`title` = 'SomeAlbum' AND `albums`.`id` != 38 LIMIT 1
↳ app/controllers/admin/albums_controller.rb:40:in `update'
Image Create (41.2ms) INSERT INTO `images` (`file_name`, `title`, `alt`, `author`, `copyright`, `created_at`, `updated_at`) VALUES (NULL, NULL, NULL, NULL, NULL, '2022-05-20 09:18:46', '2022-05-20 09:18:46')
↳ app/controllers/admin/albums_controller.rb:40:in `update'
AlbumImage Create (0.2ms) INSERT INTO `album_images` (`album_id`, `image_id`, `created_at`, `updated_at`) VALUES (38, 231, '2022-05-20 09:18:46', '2022-05-20 09:18:46')
↳ app/controllers/admin/albums_controller.rb:40:in `update'
Image Create (0.3ms) INSERT INTO `images` (`file_name`, `title`, `alt`, `author`, `copyright`, `created_at`, `updated_at`) VALUES ('some-image.jpg', NULL, NULL, 'Some Author', 'SomeCopyRight', '2022-05-20 09:18:46', '2022-05-20 09:18:46')
↳ app/controllers/admin/albums_controller.rb:40:in `update'
ImageFund Create (0.3ms) INSERT INTO `image_funds` (`image_id`, `fund_id`, `created_at`, `updated_at`) VALUES (232, 1, '2022-05-20 09:18:46', '2022-05-20 09:18:46')
↳ app/controllers/admin/albums_controller.rb:40:in `update'
ImageFund Create (0.2ms) INSERT INTO `image_funds` (`image_id`, `fund_id`, `created_at`, `updated_at`) VALUES (232, 6, '2022-05-20 09:18:46', '2022-05-20 09:18:46')
↳ app/controllers/admin/albums_controller.rb:40:in `update'
AlbumImage Create (0.3ms) INSERT INTO `album_images` (`album_id`, `image_id`, `created_at`, `updated_at`) VALUES (38, 232, '2022-05-20 09:18:46', '2022-05-20 09:18:46')
↳ app/controllers/admin/albums_controller.rb:40:in `update'
TRANSACTION (3.1ms) COMMIT
↳ app/controllers/admin/albums_controller.rb:40:in `update'
Redirected to http://localhost:3000/admin/albums/38
Completed 302 Found in 2136ms (ActiveRecord: 52.4ms | Allocations: 46882)
This is is my form:
<%= form_for [:admin, #album], html: {role: 'form' } do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.fields_for :images, Image.new do |ff| %>
<div class='form-data'>
<%= ff.label :file_name, class: 'form-label' %>
<%= ff.file_field :file_name, multiple: :true, name: "album[images_attributes][][file_name]", class: 'form-field' %>
</div>
<div class="form-data">
<%= ff.label :author, class: "form-label" %>
<%= ff.text_field :author, name: "album[images_attributes][][author]", class: "form-field" %>
</div>
<div class="form-data">
<%= ff.label :copyright, class: "form-label" %>
<%= ff.text_field :copyright, name: "album[images_attributes][][copyright]", class: "form-field" %>
</div>
<div class="form-data">
<%= ff.label :fund, class: "form-label" %>
<% Fund.all.each do |fund| %>
<%= check_box_tag "album[images_attributes][][funds_ids][]", fund.id, ff.object.funds.include?(fund), class: "checkbox" %>
<%= fund.name %>
<% end %>
</div>
<% end %>
<div class='actions create'>
<%= f.submit 'Save' %>
</div>
<% end %>
Why does images_attributes get an array of two elements, instead of just one?
I hope someone can put me into the right direction. Thank you very much in advance!
In the Albums controller I set the permitted parameters for images:
private
def album_params
params.require(:album).permit(:title, :section_id, images_attributes: [:alt, :author, :copyright, :file_name, :title, funds_ids: []])
end
I was able to get it running. I needed to set include_hidden: false in the file_field
<%= image.file_field :file_name, include_hidden: false, multiple: :true, name: "album[images_attributes][][file_name]", class: 'form-field' %>
Before updating Rails and Carrierwave this used to work without this option.
TLDR; Set this in config/application.rb and it will solve all your file fields issues.
config.active_storage.multiple_file_field_include_hidden = false
# or this, but beware of load order, you can probably put this in an initializer ( untested)
ActionView::Helpers::FormHelper.multiple_file_field_include_hidden = false
On rails 7 a new configuration option has been introduced in ActionView::Helpers::FormHelper
By default it's false. and it's used here in #field_field
However, ActiveStorage in rails 7 overrides it to true by default, especially if you set config.load_defaults 7.0 because of a new feature to handle empty collections, cf.
So instead of adding include_hidden: false on ALL your file fields, especially if you have a big application, you can set this mattr_accessor either on activestorage config, or directly on the FormHelper class.
Related
I'm using grouped_collection_select in filtering out associated information in a rails 5 form.
The first grouped_collection_select works with the Property filtering out associated data relevant to Co-operators. But, the second grouped_collection_select does work when filtering Fields associated to a Property, but comes up with an error when trying to save:
1 error prohibited this trial from being saved:
Field must exist
Form
<%= form_with(model: trial, local: true) do |f| %>
<label>Co-operator</label>
<%= f.collection_select :cooperator_id, Cooperator.order('last_name'), :id, :full_name %>
<label>Property</label>
<%= f.grouped_collection_select :property_id, Cooperator.order('last_name'), :properties, :full_name, :cooperator_id, :name %>
<label>Field</label>
<%= f.grouped_collection_select :field_id, Property.order('name'), :fields, :name, :property_id, :field_name %>
<%= f.submit 'Submit' %>
<% end %>
When I change the grouped_collection_select to a collection_select it works as should. But, this does't suit what i'm needing.
<%= f.collection_select :field_id, Field.all, :id, :field_name %>
Trials Controller
def trial_params
params.require(:trial).permit(:cooperator_id, :field_id, :property_id)
end
Trial Model
class Trial < ApplicationRecord
belongs_to :cooperator
belongs_to :property
belongs_to :field
end
Log
Processing by TrialsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"THfy+JGBYbNvzurUscPfP8LQbnnvIz1HBEfeFRiZrocXtiu4ayncEA8cNBA2IkPgcphLoa0QWsEueFBEP29OXA==", "trial"=>{"cooperator_id"=>"2", "property_id"=>"2", "field_id"=>""}, "commit"=>"Create trial", "id"=>"11"}
Cooperator Load (0.5ms) SELECT "cooperators".* FROM "cooperators" WHERE "cooperators"."id" = $1 LIMIT $2 [["id", 2], ["LIMIT", 1]]
↳ app/controllers/trials_controller.rb:49
Property Load (0.4ms) SELECT "properties".* FROM "properties" WHERE "properties"."id" = $1 LIMIT $2 [["id", 2], ["LIMIT", 1]]
↳ app/controllers/trials_controller.rb:49
Field Load (0.4ms) SELECT "fields".* FROM "fields"
↳ app/views/trials/_form.html.erb:39
Rendered trials/_form.html.erb (15.3ms)
Rendered trials/edit.html.erb within layouts/application (16.6ms)
Rendered partials/_top_nav.html.erb (0.5ms)
Rendered partials/_main_nav.html.erb (0.8ms)
Completed 200 OK in 63ms (Views: 46.9ms | ActiveRecord: 8.2ms)
The form code doesn't look right to me, the first grouped collection should be something like:
<%= f.grouped_collection_select :property_id, Cooperator.order('last_name'), :properties, :full_name, :id, :name %> # Notice that the cooperator_id is replaced with id because this needs to be the value that should be set on selection. Your original code would set it to the ID of the Cooperator instead of Property.
Similarly, the second one should be something like:
<%= f.grouped_collection_select :field_id, Property.order('name'), :fields, :name, :id, :field_name %>
Good day all, I'm pulling my hair out on this one, I've seen similar posts but none of them get me in the direction I'm trying to go.
That said, I've got a pretty complex app that's relying heavily on nested resources and name-spacing, when I save a record it saves perfectly
and redirects correctly. When I update that same record the URL changes but not as I would expect. I understand the flow from edit to update and
the set_input call pulling the params[:id], what I don't understand is why the URL is changing the parents resource to reflect the record ID.
/servers/1/features/rsyslog_inputs/12/edit"
changes to the following after update
/servers/12/features/rsyslog_inputs/12/edit"
LOGS
Started GET "/servers/1/features/rsyslog_inputs/12/edit" for 127.0.0.1 at 2017-12-08 12:27:55 -0600
Processing by Features::RsyslogInputsController#edit as HTML
Parameters: {"server_id"=>"1", "id"=>"12"}
RsyslogInput Load (0.6ms) SELECT "rsyslog_inputs".* FROM "rsyslog_inputs" WHERE "rsyslog_inputs"."id" = $1 LIMIT $2 [["id", 12], ["LIMIT", 1]]
Rendering features/rsyslog_inputs/edit.html.erb within layouts/application
Rendered shared/_error_messages.html.erb (0.4ms) [cache miss]
Rendered features/rsyslog_inputs/_form.html.erb (4.3ms) [cache miss]
Rendered features/rsyslog_inputs/edit.html.erb within layouts/application (6.5ms)
Rendered layouts/_shim.html.erb (0.5ms) [cache miss]
User Load (1.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 1], ["LIMIT", 1]]
Rendered layouts/_navbar_top.html.erb (0.9ms) [cache miss]
Rendered layouts/_navbar_side.html.erb (0.5ms) [cache miss]
Completed 200 OK in 90ms (Views: 84.7ms | ActiveRecord: 1.7ms)
Here the PATCH has modified the servers/:id to reflect the id of the rsyslog_inputs and not retained its "1" as shown above
Started PATCH "/servers/12/features/rsyslog_inputs/12" for 127.0.0.1 at 2017-12-08 12:27:58 -0600
Processing by Features::RsyslogInputsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"dFt61NcQWXoKpmScrkngT47ZxDdhzMUcCyJ5fZKrdbaOVqKfLXMVeBUj20zKKHQ8wGe4fi2QEw98cLviyO4wQw==", "rsyslog_input"=>{"inputs_interface"=>"eth04", "inputs_ip_address"=>"1.1.1.1", "inputs_input_type"=>"tcp", "inputs_port_number"=>"22", "inputs_input_name"=>"test02", "inputs_tls"=>"0"}, "commit"=>"Save Input", "appliance_id"=>"12", "id"=>"12"}
RsyslogInput Load (0.7ms) SELECT "rsyslog_inputs".* FROM "rsyslog_inputs" WHERE "rsyslog_inputs"."id" = $1 LIMIT $2 [["id", 12], ["LIMIT", 1]]
(0.6ms) BEGIN
Server Load (1.0ms) SELECT "servers".* FROM "servers" WHERE "servers"."id" = $1 LIMIT $2 [["id", 1], ["LIMIT", 1]]
SQL (1.0ms) UPDATE "rsyslog_inputs" SET "inputs_interface" = $1, "updated_at" = $2 WHERE "rsyslog_inputs"."id" = $3 [["inputs_interface", "eth04"], ["updated_at", "2017-12-08 18:27:58.904817"], ["id", 12]]
(0.8ms) COMMIT
Redirected to http://localhost:3000/servers/12/features/rsyslog_inputs
Completed 302 Found in 12ms (ActiveRecord: 4.0ms)
Controller
class Features::RsyslogInputsController < ApplicationController
before_action :set_input, only: [:show, :edit, :update, :destroy]
def index
# Let's search for all inputs associated with the corresponding appliance
#inputs = RsyslogInput.where(server_id: params[:server_id])
end
def create
#input = RsyslogInput.new(input_params)
#input.build_server
#input.server_id = params[:server_id]
if #input.save
flash[:notice] = "Input was successfully saved."
redirect_to server_features_rsyslog_inputs_path
else
render('new')
end
end
def destroy
if #input.destroy
flash[:notice] = "Input was successfully destoryed."
redirect_to server_features_rsyslog_inputs_path
else
flash[:alert] = "Unable to destroy #{#input.inputs_input_name}"
end
end
def update
if #input.update(input_params)
flash[:notice] = "Input was successfully updated"
redirect_to server_features_rsyslog_inputs_path
else
render('edit')
end
end
def new
#input = RsyslogInput.new
end
def edit; end
def show ;end
private
def set_input
#input = RsyslogInput.find(params[:id])
end
def input_params
params.require(:rsyslog_input).permit(:inputs_interface,
:inputs_input_type,
:inputs_ip_address,
:inputs_port_number,
:inputs_input_name,
:inputs_tls,
:server_id)
end
end
Form
<%= form_for ([:server, :features, #input]) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<br/>
<div class="form-group clients-form-container">
<%= f.label :inputs_interface, 'Input interface:', class: 'col-3 col-form-label' %>
<div class="col-3">
<%= f.text_field :inputs_interface, class: 'form-control', placeholder: 'Enter Interface: (e.g. eth0)' %>
</div>
<br/>
<%= f.label :inputs_ip_address, 'Input IP Address:', class: 'col-3 col-form-label' %>
<div class="col-3">
<%= f.text_field :inputs_ip_address, class: 'form-control', placeholder: 'Enter IP Address:' %>
</div>
<br/>
<%= f.label :inputs_input_type, 'Input type:', class: 'col-3 col-form-label' %>
<div class="col-3">
<%= f.text_field :inputs_input_type, class: 'form-control', placeholder: 'TCP/UDP' %>
</div>
<br/>
<%= f.label :inputs_port_number, 'Input port number:', class: 'col-3 col-form-label' %>
<div class="col-3">
<%= f.text_field :inputs_port_number, class: 'form-control', placeholder: 'Enter Port:' %>
</div>
<br/>
<%= f.label :inputs_input_name, 'Input Name:', class: 'col-3 col-form-label' %>
<div class="col-3">
<%= f.text_field :inputs_input_name, class: 'form-control', placeholder: 'Enter Ruleset Name)' %>
</div>
<br/>
<div class="form-inline">
<%= f.label :inputs_tls, 'Enable TLS:', class: 'col-1 col-form-label' %>
<div class="col-3">
<%= f.check_box :inputs_tls, class: 'form-control check-box-alignment' %>
</div>
</div>
</div>
<%= f.submit 'Save Input', class: 'btn btn-primary btn-lg' %>
<%= link_to 'Cancel', :back, class: 'btn btn-secondary region-btn btn-lg' %>
<% end %>
<br/>
Routes
resources :servers do
namespace :features do
resources :rsyslog_inputs
resources :rsyslog, only: :index
end
end
server_features_rsyslog_inputs GET /servers/:server_id/features/rsyslog_inputs(.:format) features/rsyslog_inputs#index
POST /servers/:server_id/features/rsyslog_inputs(.:format) features/rsyslog_inputs#create
new_server_features_rsyslog_input GET /servers/:server_id/features/rsyslog_inputs/new(.:format) features/rsyslog_inputs#new
edit_server_features_rsyslog_input GET /servers/:server_id/features/rsyslog_inputs/:id/edit(.:format) features/rsyslog_inputs#edit
server_features_rsyslog_input GET /servers/:server_id/features/rsyslog_inputs/:id(.:format) features/rsyslog_inputs#show
PATCH /servers/:server_id/features/rsyslog_inputs/:id(.:format) features/rsyslog_inputs#update
PUT /servers/:server_id/features/rsyslog_inputs/:id(.:format) features/rsyslog_inputs#update
DELETE /servers/:server_id/features/rsyslog_inputs/:id(.:format) features/rsyslog_inputs#destroy
server_features_rsyslog_index GET /servers/:server_id/features/rsyslog_inputs(.:format) features/rsyslog_inputs#index
seeing your forms, controller and the requirement, i would advice that you use the route helpers and pass in the appropriate parameters there
like in your form explicitly set the form url to
server_features_rsyslog_input(server_id: params[:server_id], id: #input.id)
and in your controller too pass in the parameters explicitly
So this actually turned out to be a redirection issue in the update method. I wasn't specifying the server_id which wouldn't allow the redirection back to the index based on the server.
I am wondering if someone could tell me why I am getting this error "undefined method '[]' for nil:NilClass". This happens when I remove a picture with cocoon and try update. The method works fine for adding pictures to the edited gallery but I am getting this error when removing and updating. I tried using unless #pictures.blank? end I am assuming the problem is when cocoon removes the picture but I am not sure what to do from there. the server error is,
Started PATCH "/galleries/41" for ::1 at 2017-05-07 16:03:02 +1000
Processing by GalleriesController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"cG1UXCvODhYzqqAr++EAn8GvMVk7+t/eASkzDDOoPmJfw3l6ax/F2xXMhvs7FcrJ3LOuTd0sks5+2fb86kQv0Q==", "gallery"=>{"name"=>"Hellooo", "cover"=>"123456", "pictures_attributes"=>{"0"=>{"_destroy"=>"1", "id"=>"47"}, "1"=>{"_destroy"=>"1", "id"=>"48"}}}, "commit"=>"Update Gallery", "id"=>"41"}
Gallery Load (0.0ms) SELECT "galleries".* FROM "galleries" WHERE "galleries"."id" = ? LIMIT ? [["id", 41], ["LIMIT", 1]]
Unpermitted parameter: pictures_attributes
(0.0ms) begin transaction
User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
(0.0ms) commit transaction
Completed 500 Internal Server Error in 4ms (ActiveRecord: 0.0ms)
NoMethodError (undefined method `[]' for nil:NilClass):
...
Perhaps if someone could explain this to me would be great!
_form.html.erb
<%= form_for(#gallery, multipart: true) do |f| %>
<div class="field">
<%= f.label :name %>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :cover %>
<%= f.text_field :cover %>
</div>
<div id="pictures">
<%= f.fields_for :pictures do |pic| %>
<%= render 'picture_fields', f: pic %>
</div>
<% end %>
<div class="links">
<%= link_to_add_association 'add picture', f, :pictures %>
<%= f.submit %>
</div>
<% end %>
_picture_fields.html.erb
<div class="nested-fields">
<div class="field">
<%= f.label :picture %>
<%= f.file_field :picture, multiple: true, name: "pictures[picture][]" %>
<%= link_to_remove_association "remove picture", f %>
</div>
</div>
GalleriesController
def update
#gallery = Gallery.find(params[:id])
if #gallery.update(gallery_params)
params[:pictures][:picture].each do |pic|
#pictures = #gallery.pictures.create!(picture: pic)
end
flash[:success] = "Gallery Updated!"
redirect_to root_url
else
render 'edit'
end
end
Edit: Added gallery_params
def gallery_params
params.require(:gallery).permit(:id, :name, :user_id, :cover, picture_attributes: [:id, :gallery_id, :picture, :_destroy])
end
EDIT: Added create action and server log using cocoon
def create
#user = User.first
#gallery = #user.galleries.build(gallery_params)
if #gallery.save
flash[:success] = "Picture created!"
redirect_to root_url
else
render 'new'
end
end
server log
Started POST "/galleries" for ::1 at 2017-05-10 13:18:43 +1000
Processing by GalleriesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"XU3z2jMdbselPJZ2SdZdGPwiAebiPznt8GWRqmbv8LM/MIxO+sNo1z2NTaDQ3nJNm0qaBJ66ny5254MPpHZaQQ==", "gallery"=>{"name"=>"Hello", "cover"=>"123456", "pictures_attributes"=>{"1494386318553"=>{"picture"=>#<ActionDispatch::Http::UploadedFile:0xac59228 #tempfile=#<Tempfile:C:/Users/Lee/AppData/Local/Temp/RackMultipart20170510-7596-16xlrir.jpg>, #original_filename="Skateboard 1.jpg", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"gallery[pictures_attributes][1494386318553][picture]\"; filename=\"Skateboard 1.jpg\"\r\nContent-Type: image/jpeg\r\n">, "_destroy"=>"false"}, "1494386321001"=>{"picture"=>#<ActionDispatch::Http::UploadedFile:0xac59150 #tempfile=#<Tempfile:C:/Users/Lee/AppData/Local/Temp/RackMultipart20170510-7596-jxo0st.jpg>, #original_filename="Skateboard 2.jpg", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"gallery[pictures_attributes][1494386321001][picture]\"; filename=\"Skateboard 2.jpg\"\r\nContent-Type: image/jpeg\r\n">, "_destroy"=>"false"}}}, "commit"=>"Create Gallery"}
User Load (0.0ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT ? [["LIMIT", 1]]
(0.0ms) begin transaction
User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
(0.0ms) rollback transaction
Rendering galleries/new.html.erb within layouts/application
Rendered galleries/_picture_fields.html.erb (1.0ms)
Rendered galleries/_picture_fields.html.erb (0.5ms)
Rendered galleries/_picture_fields.html.erb (0.5ms)
Rendered galleries/_form.html.erb (42.0ms)
Rendered galleries/new.html.erb within layouts/application (58.5ms)
Completed 200 OK in 157ms (Views: 139.3ms | ActiveRecord: 0.0ms)
Mmmm. Confused. There is no params[:pictures] so that is obviously nil (check the log you posted at the top). So that is causing the error. If you are looking for the pictures posted, you should refer to params[:pictures_attributes], but not even sure what you are trying to do there: create an empty picture (again?) for each posted pictures? The pictures are saved by doing the gallery.update(gallery_params).
Note: iterating over the posted params is imho definitely wrong, because if one is deleted, it will still be posted with the nested parameter _destroy set to true, so it can be deleted correctly from the database, or if a picture already existed, it will also be posted again (and not saved, since it already exists).
[EDIT] Add short solution:
use f.fields_for :pictures in your view: this will iterate over the existing pictures a gallery has, and will allow to delete/edit existing, and add new pictures to a gallery
fix your gallery_params and allow pictures_attributes (instead of the singular form)(otherwise nothing is saved)
in your controller just write #gallery.update_attributes(gallery_params) and do not iterate over params[:pictures] at all (remove that part) and it should just work (because the update_attributes will already have done this, at least if you want to iterate manually use pictures_attributes)
It looks like your gallery_params method is not permitting your pictures_attributes. You didn't post that code but I noticed in the error log Unpermitted parameter: pictures_attributes which means that your strong parameters(the gallery_params method) is filtering those parameters out.
Basically the whole point of the strong parameters is to make sure that you only pass through keys that you actually want to get passed through. So your controller is like "Nobody told me I am supposed to accecpt picture_attributes so I won't allow them through." Then your code is expecting there to be a picture object in the pictures array, but the pictures array doesn't have the picture object causing an error.
Can you post the code for gallery params? Can you also post the contents of params? Full disclosure: I don't really know rails 5 so there could be some other stuff going on.
I want to make a simple form_forbut that doesn't work fully.
I have two table:
Users -> has_many -> Cvs
this is my form :
<%= form_for(:cvs, action: "create", html: { method: :post }) do |f| %>
Nom : <%= f.text_field :nom %><br />
<%= f.submit %>
<% end %>
In my controller:
def create
#cv = Cv.new(cv_params)
#cv.save
end
With cv_params :
def cv_params
params.require(:cv).permit(:nom)
end
In my route.rb :
post 'createcv' => 'static_pages#createcv'
My controller is static_pages and my view is createcv
The field appear when I load the view, I put something but nothing is create in the table (there is no error). How can I correct that please?
EDIT:
The logs
Started GET "/createcv" for ::1 at 2015-06-16 17:22:03 +0200
Processing by StaticPagesController#createcv as HTML
User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
Cv Load (0.0ms) SELECT "cvs".* FROM "cvs" WHERE "cvs"."user_id" = ? [["user_id", 1]]
Rendered static_pages/createcv.html.erb within layouts/application (10.0ms)
Rendered layouts/_shim.html.erb (1.0ms)
Rendered layouts/_header.html.erb (2.0ms)
Rendered layouts/_footer.html.erb (1.0ms)
Completed 200 OK in 582ms (Views: 570.6ms | ActiveRecord: 0.0ms)
Started POST "/createcv" for ::1 at 2015-06-16 17:22:12 +0200
Processing by StaticPagesController#createcv as HTML
Parameters: {"utf8"=>"V", "authenticity_token"=>"28oSelskM87GZ/geLj6yl3tOrtvKktH/poBasO4pyt7I2QNKxw9HX4J+yS3cmisuzmGOGnr+6IxZdh+uQGDRDQ==", "cvs"=>{"nom"=>"hjsvqsv"}, "commit"=>"Save Cvs"}
User Load (1.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
Cv Load (0.0ms) SELECT "cvs".* FROM "cvs" WHERE "cvs"."user_id" = ? [["user_id", 1]]
Rendered static_pages/createcv.html.erb within layouts/application (11.0ms)
Rendered layouts/_shim.html.erb (0.0ms)
Rendered layouts/_header.html.erb (1.0ms)
Rendered layouts/_footer.html.erb (0.0ms)
Completed 200 OK in 643ms (Views: 629.0ms | ActiveRecord: 1.0ms)
params.require(:cv).permit(:nom)
should be
params.require(:cvs).permit(:nom)
cause all params are nested inside :cvs not :cv
also, looking at your logs and route:
Processing by StaticPagesController#createcv
you need to rename your action to createcv.
Anyway, the routing in your app seems to be wrong... Unless you want it that way.
Ideally you should do something like this:
in static_pages controller, action createcv you'll initiate new CV object:
def createcv
...
#cv = Cv.new
end
and in createcv.html.erb the form would be like this:
<%= form_for #cv do |f| %>
Nom : <%= f.text_field :nom %><br />
<%= f.submit %>
<% end %>
rails will know that #cv in the form is a new object, and it will add the proper route to the form, that will point (depending on your app) to /cvs with post method.
That means when you submit the cv, action create from cv_controller should handle the rest of the process.
In this case you won't need the route you added, it should be there after you added
resources :cvs
This is just an example that might not fit your needs, cause I wouldn't know how did you named your models, controllers, etc..
The answer of Rajarshi Das is fine, only it seems to me that you want to open your form by visiting /createcv. so change your routes to:
# routes.rb
get '/createcv', to: 'static_pages#new'
post 'create', to: 'static_pages#create'
# static_pages controller
def new
#cv = Cv.new
end
def create
#cv = Cv.new(cv_params)
if #cv.save
flash[:alert] = 'Cv created!'
else
render 'new'
flash[:alert] = 'Error in form'
end
private
def cv_params
params.require(:cv).permit(:nom) # :cv must be singular
end
# static_pages/new.html.erb view
<%= form_for #cv do |f| %>
<p>
<%= f.label :nom %>
<%= f.text_field :nom %>
</p>
<%= f.submit %>
<% end %>
I have a Rails app, with 2 models : a User model and a Micropost model, from the RoR tutorial.
I implemented the whole Twitter app, to get started with a Rails.
Now I wanted to use the code I have to create a ride share application : people posting rides that they are going to make (when they drive), apply to a ride when they want to be a passenger, following users to get their rides on their feed (instead of just posts) and being followed by other users. We see that a "user" actually plays 2 roles : driver and passenger. I'm good with the driver : it's just the author of the post, no change to make.
But not passenger...
What I want : have a "Hop in" button on each ride post -- user clicks, the button turns to "Jump off" and we have a record that gets created in the db, in the PassengerRide table (ride_id, passenger_id) // when we click on "Jump off" the button turns to "Hop in" and the record that had been saved gets deleted from the PassengerRide table.
What I did : I tried to mimic the implementation of the following and adapt to what I want
1) generated the PassengerRide table (many to many relation between a User and a Micropost)
with
rails generate model PassengerRide ride_id:integer passenger_id:integer
2) in passenger_ride.rb :
attr_accessible :ride_id
EDIT: I removed this hoping it'd fix the problem and it didn't solve the problem.
3)established the associations! (remember: I only have a User table and a Micropost table)
in user.rb
has_many :passenger_rides, foreign_key: "passenger_id", dependent: :destroy
has_many :rides, through: :passenger_rides, class_name: "Micropost"
in passenger_ride.rb
belongs_to :passenger, class_name: "User"
belongs_to :ride, class_name: "Micropost"
in micropost.rb
has_many :passenger_rides, foreign_key: "ride_id", dependent: :destroy
has_many :passengers, through: :passenger_rides, source: :passenger, class_name: "User"
4) methods in the user model to create the passenger_ride records
def hopped_in?(ride)
self.passenger_rides.find_by_ride_id(ride.id)
end
def hop_in!(ride)
self.passenger_rides.create!(ride_id: ride.id)
end
def jump_off!(ride)
self.passenger_rides.find_by_ride_id(ride.id).destroy
end
5) add rides to the user controller
in routes.rb
resource :users do
member do
get :rides
end
end
6) views :
in app/views/microposts/_hopin.html.erb
<%= form_for(current_user.rides.build(ride_id: #micropost.id)) do |f| %>
<div><%= f.hidden_field :ride_id %></div>
<%= f.submit "Hop in", :class => "btn btn-large btn-primary" %>
<% end %>
in app/views/microposts/_jumpoff.html.erb
<%= form_for(current_user.rides.find_by_ride_id(#micropost),
html: { method: :delete }) do |f| %>
<%= f.submit "Jump off", :class => "btn btn-large" %>
<% end %>
in app/views/microposts/_ride_form.html.erb
<div id="ride_form">
<% if current_user.hopped_in?(#micropost) %>
<%= render 'microposts/jumpoff' %>
<% else %>
<%= render 'microposts/hopin' %>
<% end %>
</div>
The local server rendered the following :
Started GET "/" for 127.0.0.1 at 2012-03-30 21:39:06 -0400
Processing by PagesController#home as HTML
←[1m←[36mUser Load (0.0ms)←[0m ←[1mSELECT "users".* FROM "users" WHERE "users
"."remember_token" = 'R8o1mYu49bhrsrIyIPO-ow' LIMIT 1←[0m
←[1m←[35m (0.0ms)←[0m SELECT DISTINCT "users".id FROM "users" INNER JOIN "rel
ationships" ON "users"."id" = "relationships"."followed_id" WHERE "relationships
"."follower_id" = 3
←[1m←[36m (1.0ms)←[0m ←[1mSELECT COUNT(*) FROM "microposts" WHERE "microposts
"."user_id" = 3←[0m
Rendered shared/_user_info.html.erb (4.0ms)
←[1m←[35m (0.0ms)←[0m SELECT COUNT(*) FROM "users" INNER JOIN "relationships"
ON "users"."id" = "relationships"."followed_id" WHERE "relationships"."follower
_id" = 3
←[1m←[36m (0.0ms)←[0m ←[1mSELECT COUNT(*) FROM "users" INNER JOIN "relationsh
ips" ON "users"."id" = "relationships"."follower_id" WHERE "relationships"."foll
owed_id" = 3←[0m
←[1m←[35m (0.0ms)←[0m SELECT COUNT(*) FROM "microposts" INNER JOIN "passenger
_rides" ON "microposts"."id" = "passenger_rides"."ride_id" WHERE "passenger_ride
s"."passenger_id" = 3
Rendered shared/_stats.html.erb (15.0ms)
←[1m←[36m (0.0ms)←[0m ←[1mSELECT COUNT(*) FROM "microposts" WHERE (user_id IN
(1) OR user_id = 3)←[0m
←[1m←[35mMicropost Load (0.0ms)←[0m SELECT "microposts".* FROM "microposts" W
HERE (user_id IN (1) OR user_id = 3) ORDER BY microposts.created_at DESC LIMIT 3
0 OFFSET 0
←[1m←[36mUser Load (0.0ms)←[0m ←[1mSELECT "users".* FROM "users" WHERE "users
"."id" = 3 LIMIT 1←[0m
←[1m←[35mPassengerRide Load (0.0ms)←[0m SELECT "passenger_rides".* FROM "pass
enger_rides" WHERE "passenger_rides"."passenger_id" = 3 AND "passenger_rides"."r
ide_id" IS NULL LIMIT 1
WARNING: Can't mass-assign protected attributes: ride_id
Rendered microposts/_hopin.html.erb (4.0ms)
Rendered microposts/_ride_form.html.erb (9.0ms)
Rendered shared/_feed_item.html.erb (15.0ms)
Rendered shared/_feed.html.erb (20.0ms)
Rendered pages/home.html.erb within layouts/application (46.0ms)
Completed 500 Internal Server Error in 155ms
ActionView::Template::Error (undefined method `ride_id' for #<Micropost:0x5f53a1
0>):
1: <%= form_for(current_user.rides.build(ride_id: #micropost.id)) do |f| %>
2: <div><%= f.hidden_field :ride_id %></div>
3: <%= f.submit "Hop in", :class => "btn btn-large btn-primary" %>
4: <% end %>
app/views/microposts/_hopin.html.erb:2:in `block in _app_views_microposts__hop
in_html_erb___661389729_52209444'
app/views/microposts/_hopin.html.erb:1:in `_app_views_microposts__hopin_html_e
rb___661389729_52209444'
app/views/microposts/_ride_form.html.erb:6:in `_app_views_microposts__ride_for
m_html_erb___54007412_52167144'
app/views/shared/_feed_item.html.erb:12:in `_app_views_shared__feed_item_html_
erb___851424678_48417588'
app/views/shared/_feed.html.erb:3:in `_app_views_shared__feed_html_erb___10631
41135_48687708'
app/views/pages/home.html.erb:19:in `_app_views_pages_home_html_erb__74940785_
48176280'
Thank you so much for taking time to read that, I couldn't be more thorough !
Shouldn't it be passenger_rides instead of rides in the _hopin.html.erb partial? I.e.:
<%= form_for(current_user.passenger_rides.build(ride_id: #micropost.id)) do |f| %>
<div><%= f.hidden_field :ride_id %></div>
<%= f.submit "Hop in", :class => "btn btn-large btn-primary" %>
<% end %>