Rails generate link with array parameter - ruby-on-rails

Need an advice how to generate list of links with array of paramenter
/controller/action/id?pid1=1001&vid1=1002&pid2=2001&vid2=2002
/controller/action/id?pid1=1001&vid1=1002&pid2=2001&vid2=2003
/controller/action/id?pid1=7001&vid1=7002&pid2=2001&vid2=2003
Where pid is id of filter type, and vid is id of filter value.

What I assume you have is parameters in an array like so
params_array = ["a","b","c", "d"] where the first parameter is pid1, second is vid1, third is pid2, fourth is vid2
if this is the setup, then try this:
link_to "this is some link text", some_path, :pid1 => params_array[0], :vid2 => params_array[1] %>
etc... there are better ways to do this with loops/etc. to format the params better, but in order to do so I need to know how your original params are like.
EDIT: Again, I'm really not sure how your data is formatted so for me to be able to give you any more useful help, you'll need to expand the question with more data.
What I can tell you though is that if you wanted to have a loop to go through and merge the params, you could do so like this:
pid_parameters = params_array.each_with_index.map {|e, i| {"#{i%2==0 ? "pid" : "vid"}#{i+1}" => a[i]}}
and then link_to "this is some link text", some_path, pid_parameters which will produce something like:
/controller/action/id?pid1=1001&vid2=1002&pid3=2001&vid4=2002
again, give some more information for this to be relevant. Thanks

Related

I18n to call different Model Attribute depending on Locale?

So I am building an on-line shop and I want two language options, English and Spanish.
I am using I18n as you would normally do for all my static text and headings ect.
But, I have a products Model that can have new Products created for listing on the site. This has fields like :name_en and :name_es, :description_en and :description_es ect.
When the admin uploads a new product they obviously need to add the English and the Spanish text.
Because I have only 2 locales what I would like to do i think is call something like
<%= Product.name_"#{I18n.locale.downcase}" %>
But obviously this does not work. How can i, or just can I, interpolate a method or Attribute?
Have I missed something obvious here and just going about it the wrong way or is there a way to do this along the lines of my thinking?
Any Help massively appreciated.
Thanks
You can use send method. Try something like:
<%= Product.send("name_#{I18n.locale.downcase}") %>
Just a word of explanation, the following are equal:
string = "Hello"
string.upcase
# => "HELLO"
string.send("upcase")
# => "HELLO"
Hope that puts you in proper direction!
Good luck!

what is the best way to get a portion of this url

I am creating like a link like so:
<%= link_to('', "#{issueable}/#{order.id}/issues" %>
which creates a link like this:
root/version2/parts/2418/issues
I want to be able to get the "parts" (/version2/parts/2418/issues) portion of that url when the user clicks the link to that controller method.
You can use split:
link = "root/version2/parts/2418/issues"
puts link.split('/')[2].strip
#outputs parts
link = "version2/parts/2418"
puts link.split('/')[1].strip
#outputs parts
Ruby fiddle
In other words, you've got a string "/version2/parts/2418/issues" and you want to extract the 'parts' position from it.
"/version2/parts/2418/issues".split('/')[-3]
You'll need to figure out yourself whether to get [2] from the split array or [-3]. As an added '/' in the beginning or in the end could mess it up.
You could use regex assuming you know that it starts with "version2" and also know the order_id when it gets to it.
"/version2/parts/2418/issues".match(/\/version2\/(\w+)\/2418/)
puts $1

Java ArrayList in Ruby

When I submit the form to server, Rails.logger.info params
gives
{"cgAttr"=>{"1"=>"abc,pqr", "2"=>"US"}}
and I want
{"cgAttr"=>{"1"=>"abc", "1" => "pqr", "2"=>"US"}}
PS. "1" is input text box in UI that take multiple comma-separate values ("abc,pqr") and on server I am converting that entire string into array (["abc", "pqr"]).
Can Any one point me in correct direction?
Basically, I want to create ArrayList similar to Java in my Ruby on Rails application. Does anyone know how to achieve it. (I have not tried JRuby plugin yet)
The easiest answer is to use split:
arr = params[:cgAttr]["1"].split(",")
(Also not psyched about using "1" as a parameter name.)
Can't be done, hash key must be a unique value:
{:foo => 'foo1', :foo => 'foo2'} #=> {:foo => 'foo2'}
Think about it, how would you differentiate between the two elements? my_hash[:foo] can only refer to one element, but if two elements have the same :foo key how can you distinguish between the two?
I like Dave Newtons answer, because then you can actually access them, e.g.:
my_hash[:foo][0], my_hash[:foo][1]
It can be done:
h = {}
h.compare_by_identity
a = "1"
b = "1"
h[a] = "abc"
h[b] = "pqr"
p h # {"1"=>"abc", "1"=>"pqr"}
but it doesn't feel right.

How to build sort urls on Rails?

I am working on the index page of a listing controller, which needs several sort options. Query string is needed to determine the sort option that is active for the current page. I have used a workaround for this problem by hardcoding the query string into the sort links:
=link_to "Lowest Price","/listings?sort_by=price&order=asc", :class=>"#{'active' if request.query_string =~ /sort_by=price&order=asc/ }"
But there are two problems with this. First, this is too fragile. Second, it doesn't support a search query nor any other parameters -- otherwise it breaks.
What I need is a way to change the sort options without assuming that the query string will stay intact...
Not sure if there is a best practice for doing this. I'm taking the long road and just adding helpers to parse url to hash, hash to url, and I still don't know what to do about the active link problem. It could be a while to do all that.
Any suggestions would be appreciated.
You can do this by providing key/value pairs to any URL helper. For example:
listings_url(:sort_by => "asc", :order => "asc")

Rails: Flatten array in parameter

I'm trying to flatten an array for my form.
def update
#tour = Tour.find(params[:id])
params[:tour][:hotel_ids][0] = params[:tour][:hotel_ids][0].split(',')
...
This results in:
"hotel_ids"=>[["1","2"]]
Naturally I want it to be
"hotel_ids"=>["1","2"]
My Form:
<%= text_field_tag 'tour[hotel_ids][]', nil %>
Hope anyone can help with this.
EDIT
I've gotten it to work, somehow. This might be a bad way to do it though:
I changed the text_field that get's the array from jquery to:
<%= text_field_tag 'tour[h_ids][]', nil %>
then in my controller I did:
params[:tour][:hotel_ids] = params[:tour][:h_ids][0].split(',')
And this works, I had to add h_ids to attr_accessor though. And it will probably be a big WTF for anyone reading the coder later... but is this acceptable?
This is ruby!
params[:tour][:hotel_ids][0].flatten!
should do the trick!
ps: the '!' is important here, as it causes the 'flatten' to be saved to the calling object.
pps: for those ruby-related questions I strongly suggest experimenting with the irb or script/console. You can take your object and ask for
object.inspect
object.methods
object.class
This is really useful when debugging and discovering what ruby can do for you.
Simply use <%= text_field_tag 'tour[hotel_ids]', nil %> here, and then split like you do in example.
What really happens in your example is that Rails get param(-s) tour[hotel_ids][] in request and it thinks: "ok, so params[:tour][:hotel_ids] is an array, so I'll just push every value with this name as next values to this array", and you get exactly this behavior, you have one element in params[:tour][:hotel_ids] array, which is your value ("1,2"). If you don't need (or don't want) to assign multiple values to same param then don't create array (don't add [] at the end of the name)
Edit:
You can also go easy way (if you only want answer to posted question, not solution to problem why you have now what you expect) and just change your line in controller to:
params[:tour][:hotel_ids] = params[:tour][:hotel_ids][0].split(',')
#split returns array and in your example you assigned this new array to first position of another array. That's why you had array-in-array.

Resources