Read from params[] in Rails - ruby-on-rails

I use:
<%= select( "payment", "id", { "Visa" => "1", "Mastercard" => "2"}) %>
and I get this in HTML
<select id="payment_id" name="payment[id]"><option value="2">Mastercard</option>
<option value="1">Visa</option></select>
now how can I read the payment[id] with params[], if I use params[payment[id]] I get an error.

I suppose is better to have
params[:payment][:id]
Params is a hash and can be contain some other hash.

This one had me stumbled for a couple of hours when I first started with ruby/rails. In your controller and views you can access the payment's id with either:
params[:payment][:id]
or...
params['payment']['id']
Many people prefer using symbols (:symbol) over strings because of memory usage, no matter how small the gains...

params[:payment][:id] and params[:payment][:id] is the same on surface ,
but in fact , in ruby ,you can't access the payment's id with params[:payment][:id].
because rails has changed the usage of it.

Related

How do I obtain a selected value in Ruby on Rails 2.3.8?

My select_tag is as follows.
<%= select_tag "group", options_from_collection_for_select(#groups, "id", "gname") %>
How do I obtain the selected value in my controller?
Use square brackets.
select_tag "group[]", options_for ....
Note the []. Rails will then store this as {"group" => [one option for each form]}.
If it's important to know which select provided which value, you can nest them, so
select_tag "group[bob]", ...
will provide {"group" => {"bob" => selected_option}}.
Basically, [] stores it in an array, and [key] stores it in a hash with that key.
Then in controller, you can use as:
params["group"], which should be an array of the various selects on the page.
Try puts params and check the your console to see values sent to the controller.
That should be params[:group] in your controller.

haml select_tag with constants

I'm new to Ruby and Haml, so I"m going around in circles on this. Googling isn't giving me any sample code I can use.
I can use the select_tag and populate the list from a table. But I can't figure out how to use a simple static list of items. Can someone change this to be proper Haml? Note: the source table is 'email' and the field is 'status'.
= select_tag(:email, :status, {"canceled", "pending", "success"})
I'm looking to get a dropdown list that just has the items "canceled, pending, success" in it.
The error I get is odd number list for Hash._hamlout.format_script...
Update: I found some sample code that seemed to be what I need, and it doesn't give any errors, but the dropdown box is empty:
= select_tag(:email, :status,{ "canceled" => "1", "pending" => "2", "success"=>"3"})
Here is the HTML it produces:
<select female="2" male="1" id="email" name="email">status </select >
You are using the tag helper rather than the object-oriented helper. Use select
I'd also recommend using options_for_select. Like so:
= select(:email, :status, options_for_select([["canceled", "1"], ["pending", "2"], ["success", "3"]]))
See:
http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/select
http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/options_for_select
Got it working! I need to use "Select" instead of "Select_tag". :-)
= select(:email, :status,{ "canceled" => "canceled", "pending" => "pending", "success"=>"success"})

Updating multiple records in a single submit? - Rails 3

I'm a newbie to rails and am having some difficulty...
I have a page displaying a list of records in a table and would like for the user to be able to make changes, submit the form, to run validation and persist the data.
This is what I have so far:
View:
- #people.each do |p|
%tr
%td
%input{:type => "hidden", :name => "person_id[]", :value => p.id}
%input{:name => "firstname[]", :value => p.firstname}
%td
%input{:name => "lastname[]", :value => p.lastname}
Example parameters being posted to the controller:
"person_id"=>["12", "13", "14"],
"firstname"=>["john", "joe", "mary"],
"lastname"=>["smith", "bloggs", "jane"],
At this point I am scared, because I am no longer bound to an active record. Instead I feel myself wanting to write some messy code to loop over the person_id array to see what has changed and write any changes back.
This feels bad because I have to explicitly compare each field, also if something fails due to a validation error half way through how should I rollback any changes and display the messages to the user?
I'm hoping that due to my rails ignorance this whole approach is wrong and I am missing a trick. Does anyone have any suggestions for how to approach this problem?
I suppose you have an association setup between people model and person model, by looking at the hidden person_id field in your view code.
If your associations are rightly setup, use
accepts_nested_attributes_for
and follow the Rails guides for association basics.
At this point of time, I can only help you this much, as not much information is provided in your question.

Using Multiple collection_select elements on a form with multiple models

I'm just learning rails and I've run into a bit of a snag. Let me start with a simple breakdown of my application - it's a cookbook (of sorts)
Recipes have one or more ingredients (tuna, spleens, etc)
Ingredients have one unit (ounces, pounds, etc)
Units are pulled from a lookup table
Here's a screenshot to help clarify things further:
Form Mockup
Here's my issue: my collection_select elements names should be something like unit[id][]
Instead, they're all just named unit[id]. Here's the snippet I'm using:
collection_select(
:unit,
:id,
#units,
:id,
:name,
options = {
:prompt => "Please Select",
:class => "ingredient_unit",
:name => "unit[][]",
:id => "unit:" + i.to_s()
}
);
However, this is what it is outputting:
<select id="unit_id" name="unit[id]">
<option value="">Please Select</option>
<option value="1">Ounces</option>
</select>
...
Now, in php, these dropdowns would be named unit[]. Am I going about this the wrong way?
Thanks for the help
I am not sure what the "name" option does in the "options" hash. Can you post a link to where you found documentation of that? It looks like you are using the collection select helper properly. What do you mean by "these drop downs would be named unit[]"? It might help if you tell us your end goal of this form as Rails usually just handles stuff for you. Take advantage of its magic.
Also if you are a Rails beginner, highly recommend checking out Ryan Bates' screencasts on complex forms. Here is the link to part 1:
http://railscasts.com/episodes/73-complex-forms-part-1

select_tag is sorting (strangely) [Rails]

I have a select box that looks like this (within a form_for)
<%=f.select(:whatever_id, {"blah"=>0, "blah2"=>1, "blah3"=>2, "blah4"=>3}, {:include_blank => true}) %>
and the output is good, but weird... like this:
<select id="personal_information_whatever_id" name="personal_information[whatever_id]"><option value=""></option>
<option value="1">blah2</option>
<option value="2">blah3</option>
<option value="0">blah</option>
<option value="3">blah4</option></select>
But I want it to go in order... what is happening, and how can I correct it?
Edit: I feel like the answer has to do with this
You can never be guaranteed of any
order with hashes. You could try
.sort() to sort the values in
alphabetical order.
is there anything I can use aside from a hash?
Yes, you should use an array of arrays. The easiest way with your example would be something like this:
<%=f.select(:whatever_id, [["blah", 0], ["blah2", 1], ["blah3", 2], ["blah4", 3]], {:include_blank => true}) %>
This should suffice. Take a look at the docs at api.rubyonrails.com too.
In your model, define your hash (in your case your model is "whatever" and your hash "blahs"):
BLAHS = { "blah"=>0, "blah2"=>1, "blah3"=>2 }
In the select tag where you put your hash, type
Whatever::BLAHS.sort {|a,b| a[1] <=> b[1]}
This creates an array as described in other answers, ordered by the second item (the id/numbers).
After saving, when you pull a Whatever back out of the database and want to show the field blah, do this
Whatever::BLAHS.index whatever.blah
The array of arrays mentioned by others works, but when you want to show a Whatever, how do you show the value of blah in a nice way? I recommend sticking with the hash as it solves this problem.
The problem is that the options parameter is a hash, and hashes have no guaranteed order.
This should work for you
<%= f.select(:whatever_id, ([["blah",0],["blah2",1],["blah3",2]]), {:include_blank => true}) %>
Edit in response to your comment: For collections see collection_select

Resources