Rails: How to artificially specify param key/value values through the URL? - ruby-on-rails

I have to trigger an action of a particular website. However, it is supposed to handle params with certain key/value pairs (params = {:cost => 5, :state => "NY"}). Would there be a way to specify these params values in the URL? How would I provide these key/values otherwise?

show_things_path(:cost => 5, :state => "NY")
will add those key/values to params.
Edit:
for a string URL
"/show_things?cost=5&state='NY'"

Related

Stuck with send hash with remote true

I was stuck at a point badly..when I was doing with Rails form_for submit request with remote:true with a hidden field containing array of hashes as below:
<%= f.hidden_field :staff_stat_data, :value =>[{a: "a"} , {b: "b"}] %>
then I am getting hash as a string in parameter like:
"{:a=>\"a\"} {:b=>\"b\"}"
Badly stuck with this.
You're not getting a hash, you're getting a string that kind of looks like a hash.
Remember that each parameter is just a string, that's how data is passed between clients and servers. Rails can sometimes receive an array, but only when the parameter names describe an array (e.g, "user_favourites[]").
If you want to pass a single string that represents an array or hash, you can use JSON to encode/parse the data.
In your view, first change the array to its JSON representation like this:
<%= f.hidden_field :staff_stat_data, :value => [{a: "a"} , {b: "b"}].to_json %>
Then in your controller, change it to a hash by parsing the JSON like this:
staff_stat_data = JSON.parse(params[:staff_stat_data])
This will return you an array, where each element is a hash, just like you want.
You can try this out easily in your Rails console.
json = [{a: "a"} , {b: "b"}].to_json # => "[{\"a\":\"a\"},{\"b\":\"b\"}]"
JSON.parse(json) # => [{a: "a"} , {b: "b"}]

Passing params for creating and updating a model

I wonder, is there an easier way to do the following
#controller's action
#my_model = MyModel.create field1: params[:field1],
field2: params[:field2],
field3: params[:field3],
field4: params[:field4]
# and so on.....
I would use
#my_model = MyModel.create params
but would it work since params always contains other keys added by Rails?
P.S.
The same question for updating a model (would this work properly?)
MyModel.update_attributes params
Send params as a nested hash like
{:my_model => {:field1 => 'blah', :field2 => 'blah'}, :controller => 'something', :action => 'something_else'}
This way you could just say
#my_model = MyModel.create params[:my_model]
Rails does this automatically if you have followed the conventions while creating the form.

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.

Explaining hashes in Ruby

I'm reading a book Crafting Rails Applications by Jose Valim and have come across something that I don't understand. I'm wondering if someone can explain the difference in plain English between the three types of hash below.
For example, in what way is the nested hash (as its represented in this example) a nested hash. In other contexts, I understand nested hashes, but don't get it here.
In what way is an "array" a "key" in the second example. To me it looks just like an array with four variables.
In what way is the third example a hash with "hash as key".
Nested hash
#cached[key][prefix][name][partial]
Simple hash with array as key
#cached[[key, prefix, name, partial]]
Simple hash with hash as key
#cached[:key => key, :prefix => prefix, :name => name, :partial => partial]
The nested hash, is well, a nested hash. The example given, #cached[key][prefix][name][partial], is showing you the "path" to a particular value, so in this case the hash might look something like this:
#cache = {
key => {
prefix => {
name => {
partial => "value"
}
}
}
}
For the simple hash with an array as a key, they're using that 4-element array as one of the keys in the hash.
#cache = {
[key, prefix, name, partial] => "value",
another_key => "another value"
}
For the simple hash with hash as a key, they're using that hash (note that the {}'s for the hash are optional, which may cause some confusion) as one of the keys in the hash.
#cache = {
{:key => key, :prefix => prefix, :name => name, :partial => partial} => "value",
another_key => "another value"
}
Hope that helps!
A hash simply associates key objects to value objects. The keys and values can be anything.
If a value object is itself a hash, you could call it a "nested hash" because in some sense it is inside the main hash.
If a key object is an array, then you get a "hash with array as key".
If a key object is itself a hash, then you get a "hash with hash as key".
See amfeng's answer for a good visual representation of these different cases.
You will need to be somewhat familiar with Ruby syntax to identify the different cases when you see them.
For example, to understand #cached[[key, prefix, name, partial]] you need to know that [key, prefix, name, partial] represents an array, so what you have is like #cached[array], which means an array is being used as a key.
When you see something like #cached[key][prefix] you should know that it is equivalent to (#cached[key])[prefix] so the value object (#cached[key]) is some sort of object that responds to the [] method. In this case, it is a nested hash because the author told you so, but if you didn't know that context then it is possible for it to be something else.
When you see something like #cached[:key => key, :prefix => prefix, :name => name, :partial => partial] you should know it equivalent to #cached[{:key => key, :prefix => prefix, :name => name, :partial => partial}], which means we are using as hash as a key.

convert array of parameters from form into string

I have a form with a checkboxes:
-form_tag filter_path(#page.permalink), :method => 'get' do |f|
-ftype.producers.each do |producer|
=check_box_tag "producers[]", producer.id, false
=label_tag producer.title
%br
=submit_tag 'Сортувати', :name => nil
When I send a request, it sends a hash params with an array of producers.Link then looks like that:
'/pages/:page_id/filter?producers[]=4&producers[]=5'
And I want to make it look that:
'/pages/:pages_id/filter?producers=4,5'
Please help
It shouldn't be a problem, since ?producers[]=4&producers[]=5 will be converted by the framework into params[:producers] array with value [4, 5].
Thus, you already have an array and you don't even have to parse anything.
But if your really want to submit two input values in one parameter, you'd have to employ some javascript. By default, if you have in html form two inputs with the same name, two independent values will be submitted (like in sample url you provided).
So, it's not a Rails question, it's html and javascript question.

Resources