How do i grab an id from a collection_select form? - ruby-on-rails

I can see the the id inside the parameters in the log but i cant access it in the controller.Can any body please show me how else i could do?Apparently
#city=City.find(params[:cities][:city_id]) is not doing the job.Thank you
<%= form_for :city, :url=>{:action =>"next"} do |f| %>
<%= f.collection_select(:city_id, City.all, :id, :name ,:prompt=>"Select your city") %>
<%=f.submit "continue" %>
<%end%>
Home controller
def next
#city=City.find(params[:city_id])
session[:city_id] = #city.id
redirect_to :controller=>"parks",:action =>"show"
end
In the log
Started POST "/home/next" for 127.0.0.1 at 2011-10-21 12:16:37 -0700
Processing by ParkController#show as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"7VVJ9GHcU4miYLCkSt91S674GGTScor86Tcsz7O25ik=", "city_id"=>"2", "commit"=>"continue"}
Rendered park/show.html.erb within layouts/header (2.5ms)
Completed 500 Internal Server Error in 7ms

Awww damn Im an idiot didnt see it in the beginning. You wrote
#city=City.find(params[:cities])
But it should be
#city=City.find(params[:city_id])

You wrote
<%= collection_select(nil,:city_id, City.all, :id, :name ,:prompt=>"Select your city") %>
But you should write
<%= f.collection_select(:city_id, City.all, :id, :name ,:prompt=>"Select your city") %>
Like you did for the submit button! Actually you can also add this line to the forms target:
<%= params.inspect %>
to see which values are transfered in which hash.

Umm, maybe I am wrong (not an experienced Rails dev), but don't you have to just write
params[:city_id]
?

Related

form_with does not redirect when it ought to

I'm struggling with what I think is a very simple error, and yet I don't have the Rails sophistication to detect where that error is.
I have the following form:
<%= form_with(url: '/bills/viewer', method: :get) do |f| %>
<%= f.label :congress, 'Congress (i.e. 112)' %>
<%= f.number_field :congress, class: 'form-control' %>
<%= f.label :bill_type, 'Bill type' %>
<%= f.radio_button :bill_type, 'hr' %><%= ' House of Representatives' %>
<%= f.radio_button :bill_type, 's' %><%= ' Senate' %>
<%= f.radio_button :bill_type, 'hjres' %> <%= 'House Joint Resolution' %>
<%= f.radio_button :bill_type, 'sjres' %><%= ' Senate Joint Resolution' %>
<%= f.radio_button :bill_type, 'hconres' %><%= ' House Concurrent Resolution' %>
<%= f.radio_button :bill_type, 'sconres' %><%= ' Senate Concurrent Resolution' %>
<%= f.radio_button :bill_type, 'hres' %><%= ' House Resolution' %>
<%= f.radio_button :bill_type, 'sres' %><%= ' Senate Resolution' %>
<%= f.label :bill_number, 'Bill number' %>
<%= f.number_field :bill_number, class: 'form-control' %>
<%= f.submit "Submit", class: 'form-control' %>
<% end %>
In my config/routes.rb file, I have the following line:
get '/bills/viewer', to: 'bills#show'
The idea is that I want the form to transfer the submitted information to the "show" action in my bills_controller.rb file, which I give below...
def show
#bill = Bill.where("congress = ? AND bill_type = ? AND bill_number = ?", bill_params[:congress], bill_params[:bill_type], bill_params[:bill_number]).take
if #bill.nil?
create
end
#bill_xml = RestClient.get(bill_params[:bill_link])
render :xml => #bill_xml
puts "Called to show!"
...and then for the user to be redirected to corresponding show.html.erb file, which I give below...
<% provide(:title, "#{ #bill[:congress] } #{ #bill[:bill_type].upcase } #{ #bill[:bill_number] } | ") %>
<h1><%= "#{ #bill[:congress] } #{ #bill[:bill_type].upcase } #{ #bill[:bill_number] }" %></h1>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= puts #bill_xml %>
<%= render #bill_xml %>
</div>
</div>
<% puts "RENDERED..." %>
The two "puts" lines are in there for my own debugging purpose. The one in the show method behaves as expected, and my console displays "Called to show!". The other puts line, "RENDERED..." is not displayed. Moreover, the process completes to 200 OK.
I include my console's output upon clicking "Submit" below...
Started GET "/bills/viewer?utf8=%E2%9C%93&congress=112&bill_type=hr&bill_number=1027&commit=Submit" for 127.0.0.1 at 2018-07-05 15:05:51 -0700
Processing by BillsController#show as JS
Parameters: {"utf8"=>"✓", "congress"=>"112", "bill_type"=>"hr", "bill_number"=>"1027", "commit"=>"Submit"}
Unpermitted parameters: :utf8, :commit
Unpermitted parameters: :utf8, :commit
Unpermitted parameters: :utf8, :commit
Bill Load (0.1ms) SELECT "bills".* FROM "bills" WHERE (congress = '112' AND bill_type = 'hr' AND bill_number = '1027') LIMIT ? [["LIMIT", 1]]
Unpermitted parameters: :utf8, :commit
Called to show!
Completed 200 OK in 2980ms (Views: 0.6ms | ActiveRecord: 0.7ms)
But if the form were to be redirecting to show.html.erb the console output ought to return 3XX, no?
My (evidently wrong) understanding is that when I call the show action in my bills_controller, the website should automatically redirect to the views/bills/show.html.erb page. Why is this not the case, and how can I idiomatically correctly edit my code so that the desired redirect occurs?
Help is much appreciated.
The error was resolved by setting local: true within the form_with tag. Nevertheless, I am unclear as to why
This is from Rails Guides:
"By default form_with submits forms using Ajax thereby skipping full page redirects. To make this guide easier to get into we've disabled that with local: true for now."

Updating with drop down Array rails

Update through the drop down is not working. I have a form_tag inside the form tag I have the loop. So, the value will pass in an array. How can I update the value from it.
In my Period controller I have
def period
#period = Period.all
end
def period_update
Period.update(perio_params)
end
private
def perio_params
params.require([:period][:subject_id]).permit(:subject_id)
end
In the period_update views I have
<%= form_tag perio_update_institutes_path, method: :put do %>
<% #period.each do |p|%>
<%= p.subject.name %>
<%= select_tag('subject_id', options_for_select(Subject.all.collect{ |s| [s.name, s.id]}), {prompt: 'Select Sub'})%>
<%end%>
<%= submit_tag %>
{"utf8"=>"✓",
"_method"=>"put",
"authenticity_token"=>"6LJrh2ct7VMGU6Siq/RXIMGz4kkxkVN81Jqa+eRcKb3rXq3XzBlv8gjHvjjVsPsJ4LF7ZEHF/GQ8+0906lhyUg==",
"period"=>{"subject_id"=>["2",
"2"]},
"commit"=>"Save changes"}
how can I update the subject_id array.
The ERROR is
no implicit conversion of Symbol into Integer
I have the subject model, where all the subject will be in the collection.
The Period model has the subject_id. How can I update.
I am new to rails, and I am stuck with this. Thank you for advance.
Try if it behaves differently with options_from_collection_for_select:
<%= select_tag('subject_id', options_from_collection_for_select(Subject.all, :id, :name), {prompt: 'Select Sub'}) %>

New ticket is being created when loading a new form

This is my first question on here, so I am hoping I have not asked it incorrectly.
I have a generic new action on my tickets controller. Whenever I load tickets/new, it is creating a new item in the DB and committing it.
Here is the output from the server when the page is loading.
Started GET "/tickets/new" for ::1 at 2016-02-10 21:14:47 -0800
Processing by TicketsController#new as HTML
Customer Load (0.4ms) SELECT `customers`.* FROM `customers` WHERE `customers`.`email` = 'tim#tim.com' LIMIT 1
(0.3ms) BEGIN
SQL (0.5ms) INSERT INTO `tickets` (`category`, `created_at`, `updated_at`) VALUES (3, '2016-02-11 05:14:47', '2016-02-11 05:14:47')
(6.4ms) COMMIT
Rendered tickets/_new_form.html.erb (23.3ms)
Rendered tickets/new.html.erb within layouts/application (48.4ms)
Rendered layouts/_user_nav.html.erb (0.8ms)
Rendered layouts/_navbar.html.erb (0.5ms)
Rendered layouts/_flashes.html.erb (0.5ms)
Rendered layouts/_minimal.html.erb (759.5ms)
Completed 200 OK in 893ms (Views: 822.1ms | ActiveRecord: 21.3ms)
This is the from the tickets controller.
def new
#ticket = Ticket.new
end
Here is the code for the form.
<%= form_for(#ticket, html: { class: 'form-horizontal' }) do |f| %>
<%= f.error_notification %>
<%= f.hidden_field(:category) %>
<%= f.hidden_field(:severity) %>
<br>
<%= f.form_group :summary do |f| %>
<%= f.label :summary, class: 'control-label col-md-2' %>
<div class='col-md-8'>
<%= f.text_field :summary, class: 'form-control' %>
<%= f.error_messages %>
</div>
<% end %>
<%= f.form_group :detail do |f| %>
<%= f.label :detail, class: 'control-label col-md-2' %>
<div class='col-md-8'>
<%= f.text_area :detail, class: 'form-control' %>
<%= f.error_messages %>
</div>
<% end %>
<br>
</div>
<div class="form-actions col-md-offset-2 col-md-10">
<%= f.submit 'Create', class: 'btn btn-primary' %>
<%= link_to "Cancel", tickets_path, class: 'btn' %>
</div>
<% end %>
Here are the relevant routes.
resources :tickets do
collection do
get :step_1
get :new_ticket
get :billing_new_1
get :internet_step_1
get :internet_step_2
get :internet_modem_reset
get :internet_step_1
get :internet_step_2
get :internet_create_1
get :internet_create_2
get :tv_step_1
get :tv_step_2
get :tv_step_3
get :tv_create_1
get :tv_create_2
get :tv_create_3
get :closed
get :sidenav
end
member do
put :close
end
resources :notes
resources :appointments
end
Help!!
--Tim
INSERT INTO `tickets` (`category`, `created_at`, `updated_at`) VALUES (3, '2016-02-11 05:14:47', '2016-02-11 05:14:47')
This is getting category (3) from somewhere, suggesting that there is some functionality somewhere which is saving the #ticket.
The simplest explanation I can see is that you have a before_action somewhere. It would benefit to show your entire TicketsController:
#app/controllers/tickets_controller.rb
class TicketsController < ApplicationController
before_action :set_user #-> something like this??
end
Since you're new, you can make your routes much more succinct (multiple resources):
#config/routes.rb
methods = %i(step_1 new_ticket billing_new_1 internet_step_1 internet_step_2 internet_modem_reset internet_create_1 internet_create_2 tv_step_1 tv_step_2 tv_step_3 tv_create_1 tv_create_2 tv_create_3 closed sidenav)
resources :tickets do
resources :notes, :appointments
collection do
methods.each {|method| get method }
end
put :close, on: :member
end
I ended up starting the whole ticket class over.
I think the error was in my html.
My guess is that the if statement with the bang was causing the ticket to save, because of an enum with that name on the model.
Here is what I think was the bad html.
<% if #ticket.category == :tv %>
Ok. Your tv is down, but your internet is still working.
<br>
Do you have any more details to add? If so, add them here. If not, just hit sumbit and we will open up a ticket with all of the information that you have provided us.
<% elsif #ticket.internet! %>
Ok. Your internet is down, but your tv is still working.
<br>
Do you have any more details to add? If so, add them here. If not, just hit sumbit and we will open up a ticket with all of the information that you have provided us.
<% elsif #ticket.billing %>
I am fresh out of questions.
<br>
Do you have any more details to add? If so, add them here. If not, just hit sumbit and we will open up a ticket with all of the information that you have provided us.
<% elsif #ticket.category == :internet_and_tv %>
Ok. Your cable and internet are both down.'%>
<br>
Do you have any more details to add? If so, add them here. If not, just hit sumbit and we will open up a ticket with all of the information that you have provided us.'%>
<% else #ticket.category == :plant %>
<%end%>

Rails issue with access of nested hash parameter

I have in rails the following form in a view
<%= form_for (#account) do |f| %>
<%= f.label :comments,"Comments" %>
<%=f.text_area :comments %>
<%= f.submit "Confirm",:name=>"conf" %>
<%= f.submit "Reject" %>
<% end %>
When I submit the form I get the following hash in the log before the update of the database
Started PATCH "/accounts/12" for 127.0.0.1 at 2015-08-13 21:31:18 +0200
Processing by UseractionsController#answer_with_comments as HTML
Parameters: {"utf8"=>"✓", "account"=>{"comments"=>"mycomments"}, "conf"=>"Confirm", "id"=>"12"}
I am trying to access the input in the comments text area in the controller. I tried
params[:account][:comments]
but it does not seem to work. Could anyone give me the appropriate syntax? Thanks.
EDIT
This is my controller code. Right now the if loop return false and nothing is added to the database even though there is something submitted ("mycomments" see above in the param nested hash)
if params[:bankaccount][:comments]
#bankaccount.update_attribute(:comments, params[:bankaccount][:comments])
end
It is only the appropriate syntax for your view. It assumes that you have content field on your Comment model.
<%= form_for (#account) do |f| %>
<%= f.label :comments,"Comments" %>
<%= f.fields_for :comments do |ff| %>
<%= ff.text_field :content %>
<% end %>
<%= f.submit "Confirm",:name=>"conf" %>
<%= f.submit "Reject" %>
<% end %>
You also will have to declare nested attributes in your Account model and your params hash should be different.
You should watch these two Railscasts part 1 and part 2 to learn more about nested attributes.
Since you mention strong parameters as a tag you probably want to build this a bit differently.
private
def account_params
#the permit method might need to be altered depending on your model and view
params.require(:account).permit(:comments)
end
Somewhere else in your controller you would then do:
#bankaccount.update_attributes(account_params)
Please take a read: http://edgeguides.rubyonrails.org/action_controller_overview.html#strong-parameters

Cannot get a many-to-many item to save to the database when using a form

I have a many-to-many relationship between Notes and Stacks. I am creating a form where a user can create a new note, with a title, body, and then a group of check boxes. The group of checkboxes are various Stacks. I want a user to be able to associate one or multiple Stacks with a particular note.
I am using the simple_form gem to do this. Everything is working except the Stacks will not save to the database. The title and body save, but not the Stacks. I have tested both sides of the relationship manually in the console, and they do yield the expected results -- it works.
One thing I notice when I watch what is going on in the Rails Server tab is Unpermitted parameters: stack_ids, as seen here:
Started POST "/notes" for 127.0.0.1 at 2014-10-06 16:00:21 -0600
Processing by NotesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"gMpbaYio0qkPLLrR6ICG0IJ7XNoy3Rn4RHLm3vwUU+I=", "note"=>{"title"=>"asdfs ", "body"=>"asdfasdf asfsadf ", "stack_ids"=>["1", "2", ""]}, "commit"=>"Create Note"}
Unpermitted parameters: stack_ids
My notes_controller.rb has these params:
def notes_params
params.require(:note).permit(:title, :body, :stack_id)
end
My stacks_controller.rb has these params:
def stacks_params
params.require(:stack).permit(:title, :description, :note_id)
end
Here is the form:
<%= simple_form_for #note, :html => { :class => 'form-horizontal' } do |f| %>
<%= f.input :title, placeholder: ":title", id: "note-form-title-field", class: "note-form-fields" %>
<%= f.input :body, placeholder: ":body", id: "note-form-body-field", class: "note-form-fields" %>
<%= f.association :stacks, as: :check_boxes %>
<%= f.button :submit %>
<% end %>
I have tried replacing :stack_id in the params with other variations, and always get the same result. Any ideas on how to get these Stacks to save to the database, associated with a note? Thanks.
This StackOverflow posting provides a detailed solution.
In summary, when declaring strong parameters, I needed to explicitly map the stack_ids key to an empty array in my notes_controller.rb file:
def notes_params
params.require(:note).permit(:title, :body, stack_ids: [])
end

Resources