I am using a collection select to display all the categories on the website.
<%= form.collection_select :category_id, Category.all, :id, :name, :prompt => "Select category" %>
I also included category_id in the permit params
def portfolio_params
params.require(:portfolio).permit(:name, :client, :completed, :about,:square, :cover, :category_id)
end
Shouldn't it form the association using the create method like this
def create
#portfolio = Portfolio.new(portfolio_params)
#test = portfolio_params[:category_id]
respond_to do |format|
if #portfolio.save
format.html { redirect_to #portfolio, notice: 'Portfolio was successfully created.' }
format.json { render :show, status: :created, location: #portfolio }
else
format.html { render :new }
format.json { render json: #portfolio.errors, status: :unprocessable_entity }
end
end
end
But when I look at the test variable it shows null. I am really puzzled about this. I am using rails 5 and ruby 2.3.0
Here are the params
<ActionController::Parameters
{"utf8"=>"✓",
"authenticity_token"=>"XzyeAtZF5mOXG2GdRIrlmRcPwhruAOfrvzIWTD9QUsIJ4GMytB6s38oM3NT9RIwr+B8osJWasmg2Qd0VoROTiw==",
"portfolio"=><ActionController::Parameters
{"name"=>"test",
"client"=>"",
"completed(1i)"=>"2017",
"completed(2i)"=>"5",
"completed(3i)"=>"17",
"about"=>"",
"categoy_id"=>"3"} permitted: false>,
"commit"=>"Create Portfolio",
"controller"=>"portfolios",
"action"=>"create"} permitted: false>
Related
I have a model with movies and actors and I want both to be taggeable. I know there's a gem for that but I thought I'd teach myself polymorphic associations :)
Basic functionality works (I can do stuff like amovie.tags.create etc...) but now I want forms for movies and actors where tags can be selected and deselected.
Problem : I cannot deselect a tag:
While selecting a tag (that exists) works, when I deselect a tag, I get an error. Here's the relevant code:
Movie Form:
<%= form.collection_select(:tag_ids, Tag.order(:name), :id, :name, {}, { class: 'selectize-tag', multiple: true }) %>
movies controller - update section as well as movies_params private function:
def update
respond_to do |format|
if #movie.update(movie_params)
format.html { redirect_to #movie, notice: "Movie was successfully updated." }
format.json { render :show, status: :ok, location: #movie }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: #movie.errors, status: :unprocessable_entity }
end
end
end
def movie_params
params.require(:movie).permit(:title, :runtime, :country, :release_year, :sort_title, tag_ids: [])
end
Error I get:
Mysql2::Error: Column 'taggeable_id' cannot be null
Params - I think the problem is the line that has tag IDs and one of them is ""
{"_method"=>"patch",
"authenticity_token"=>"[FILTERED]",
"movie"=>
{"title"=>"The Avengers",
"sort_title"=>"Avengers",
"release_year"=>"2012",
"country"=>"US",
"runtime"=>"143",
"tag_ids"=>["", "3"]},
"commit"=>"Update Movie",
"id"=>"48"}
So not sure what I need to do for that empty tag id there to not be submitted but rather to trigger "remove tag with ID xyz from movie abc?
I'm trying to implement a multi-select for a many to many relationship in Ruby on Rails, however I'm unable to access the array of strings representing the selected User Ids in the user_ids field.
The following is my project_params after clicking update
"project"=>{"name"=>"Project Name",
"client"=>"Client X", "project_url"=>""},
"user_ids"=>["2", "3", "4", "5"], "commit"=>"Update Project", "id"=>"1"}
The following is my ProjectsController code
def update
puts project_params[:user_ids=>[]]
respond_to do |format|
if #project.update(project_params)
format.html { redirect_to #project, notice: 'Project was successfully updated.' }
format.json { render :show, status: :ok, location: #project }
else
format.html { render :edit }
format.json { render json: #project.errors, status: :unprocessable_entity }
end
end
end
def project_params
params.require(:project).permit(:id, :name, :client, :project_url, :user_ids => [])
end
The line puts project_params[:user_ids=>[]] prints a blank line. I've also tried puts project_params[:user_ids] and puts project_params[:user_ids[]] - none of which work
The following is my _form.html.erb Code
<%= select_tag "user_ids",
options_from_collection_for_select(User.all, "id", "name", #project.user),
{ :multiple => true, :size =>10}
%>
The select tag will use the first argument as the key. Hence the values is located on:
params[:user_ids]
or if you are using form builder
<%= form_for #project do |f| %>
<%= f.select :user_ids,
options_from_collection_for_select(User.all, "id", "name", #project.user),
{ :multiple => true, :size =>10}
%>
<% end %>
then it will be available in project_params
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])
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.
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