rails object expected got string in association - ruby-on-rails

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.

Related

Rails association when you have a drop down

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>

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])

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

Passing variable to the url in rails

I am passing variable like that:
new_sub_request_path(request_id:#request.id)
so i get this url:
http://localhost:3000/sub_requests/new?request_id=1
In my controller i want to assign that request_id like that:
#sub_request = SubRequest.new(sub_request_params)
#sub_request.request_id = params[:request_id]
and my strong parameters are defined:
def sub_request_params
params.require(:sub_request).permit(:description, :diagnos, :price, :payment, :request_id)
end
But after save i have empty request_id attribute, so it seems that it is not assigned. What am I doing wrong?
EDIT:
Inspecting parameters in the console showed that i only have those attributes that are in my form.
EDIT2:
def create
#sub_request = SubRequest.new(sub_request_params)
#sub_request.request_id = params[:sub_request][:request_id]
respond_to do |format|
if #sub_request.save
format.html { redirect_to #sub_request, notice: 'Sub request was successfully created.' }
format.json { render :show, status: :created, location: #sub_request }
else
format.html { render :new }
format.json { render json: #sub_request.errors, status: :unprocessable_entity }
end
end
end
You have to define something like below for the request_id to save in sub_requests table.
In your create method add this line
#request = Request.find(params[:request_id]) and do
#sub_request.request_id = #request.id
or
You can just add a hidden_field in your form like below
<%= f.hidden_field :request_id, :value => #request.id %>
And make sure you are permitting :request_id in your sub_request_params

Setting an object attribute from a hidden field Ruby on Rails

I'm trying to update an Idea attribute challenge_id through a hidden form field. Here is the field:
<%= f.hidden_field :challenge_id, :value => #challenge.id %>
It successfully passes the challenge id as a param when an idea is created to the Idea Controller#create method:
Started POST "/ideas.js" for ::1 at 2015-06-18 15:39:49 -0400
Processing by IdeasController#create as JS
Parameters: {"utf8"=>"✓", "idea"=>{"title"=>"adsf", "description"=>"asf", "domain_tokens"=>"20", "challenge_id"=>"5"}, "commit"=>"Create Idea"}
This challenge_id => 5 should then be saved to the idea in the line #idea = Idea.new(idea_params) below:
ideas_controller.rb
def create
#idea = Idea.new(idea_params)
respond_to do |format|
if #idea.save
idea_count = #idea.user.ideas_created_count
#idea.user.update(:ideas_created_count => idea_count + 1)
#idea.domains.each do |domain|
current_user.add_points(1, category: domain.title)
end
#ideas = current_user.current_team.ideas.sort_by{|i| i.heat_index}.reverse
#ideas = #ideas.paginate(:page => params[:ideas_page], :per_page => 10)
format.html { redirect_to :back, notice: 'Idea was successfully created.' }
format.json { render :show, status: :created, location: #idea }
format.js
else
format.html { redirect_to :back, notice: "You must attach domains to your Idea." }
format.json { render json: #idea.errors, status: :unprocessable_entity }
format.js { render :create_failed }
end
end
end
.
.
def idea_params
params.require(:idea).permit(:title, :description, :challenge_id)
end
However, this challenge id isn't being saved to the idea with the other permitted idea_params, :title and :description. How can I get challenge_id to be saved to the Idea when it's created?
Instead of using hidden field, why not pass in the challenge_id in your form? Otherwise, you leave open the possibility that users can enter whatever they want in that hidden field.
Form:
form_for [#challenge, Idea.new] do |f|
And then:
def create
#challenge = Challenge.find(params[:challenge_id])
#idea = Idea.new(idea_params)
#idea.challenge_id = #challenge.id
end
I'm assuming you have challenge_id column in ideas table.
Try something like:
def create
#idea = Idea.new(idea_params)
#idea.challenge_id = params[:idea][:challenge_id]
#...
end
If you params or column you want to save it to is different, make sure to make the change, but you get the idea.

Resources