Ruby/Rails: each do loop range from another loop - ruby-on-rails

I'm using the following each do loop to pull in data from a JSON file and make it usable on my site.
<% data.games.ronedoneb.each do |s| %>
This is working great. What I'm wanting to do is to specify a range that will be used, like so:
<% data.games.ronedoneb[(0..5)].each do |s| %>
What I'm wanting to do however, is change the range (0..5) based on fields within another JSON file, the range will always be blocks of 6 so: (0..5), (6..11), (12..17) etc etc.
This is what I've tried to do is below:
<% data.games.ronedoneb[(<%= ss[:z1] %>..<%= ss[:z2] %>)].each do |s| %>
This doesn't work, I hoped that I'd be able to pull the z1 and z2 results from the first JSON file.
Is there a way that I can do this? Is there something I'm missing?
Below are examples of the JSON being used.
JSON 1
"Ar": "1",
"Br": "0",
"Round": "1",
"Game": "3",
"Date": "Thursday, 5 February 2015",
"Day": "1",
"z1": "12",
"z2": "17"
JSON 2
"Game": "1",
"AR": "9",
"Day": "1",
"GPMB": "351",
"DR": "2",
"CSB": "275",
"GPMR": "360",
"AB": "1",
"Round": "1",
"CSp10R": "60",
"GoldR": "13.2",
"DB": "2",
"CSR": "222",
"GoldB": "12.9",
"KDAR": "6.50",
"Blue": "23.7",
"CSat10B": "79",
"KB": "5",
"KDAB": "3.00",
"KR": "4",
"CSat10R": "76"

You can't use <%= in the place you did. Please try something like:
<% data.games.ronedoneb[(ss[:z1].to_i..ss[:z2].to_i)].each do |s| %>

You can use ruby's already built in enumerable method each_slice you specify the slice length and it will cut the array into slices with that length, then pass the slices to the block.
You'll probably need to convert the json into a hash, but that's easy,
data.games.ronedoneb.each_slice(5) do |slice|
slice.each do |item|
#process here
end
end

Related

Sort alphabetically hash's values in array from STRIPE API / Rails

In rails 6.1.4, I want to display the :nickname of a Product in STRIPE in DESC order. I mean S, M, L on my VIEW page and not in a random way like Stripe give us.
In their https://stripe.com/docs/api it seems we couldn't make the request on an easy way.
For this, I query #compositionsProduct = Stripe::Price.list(product: #composition.product). It returns me an Array of Hash in the data part:
=> #<Stripe::ListObject:0x3ff733e41c08> JSON: {
"object": "list",
"data": [
{"id":"price_price1","object":"price","active":true,"billing_scheme":"per_unit","created":1635150421,"currency":"eur","livemode":false,"lookup_key":null,"metadata":{},"nickname":"L","product":"prod_prod1","recurring":null,"tax_behavior":"unspecified","tiers_mode":null,"transform_quantity":null,"type":"one_time","unit_amount":4500,"unit_amount_decimal":"4500"},
{"id":"price_price2","object":"price","active":true,"billing_scheme":"per_unit","created":1635150421,"currency":"eur","livemode":false,"lookup_key":null,"metadata":{},"nickname":"S","product":"prod_prod1","recurring":null,"tax_behavior":"unspecified","tiers_mode":null,"transform_quantity":null,"type":"one_time","unit_amount":2500,"unit_amount_decimal":"2500"},
{"id":"price_price3","object":"price","active":true,"billing_scheme":"per_unit","created":1635150421,"currency":"eur","livemode":false,"lookup_key":null,"metadata":{},"nickname":"M","product":"prod_prod1","recurring":null,"tax_behavior":"unspecified","tiers_mode":null,"transform_quantity":null,"type":"one_time","unit_amount":3500,"unit_amount_decimal":"3500"}
],
"has_more": false,
"url": "/v1/prices"
}
I want to write something like this:
Stripe::Price.list(product: #composition.product).sort_by([:nickname].reverse) but it obviously doesn't work.
I can iterate over these 3 lines, but I need to linked_to them on their Price page respectively.
<% #compositionsProduct.map do |compoPrice| %>
<%= link_to "#{compoPrice.nickname}", composition_path(compoPrice.id) %>
<% end %>
This is my farest point: #compositionsProduct.sort_by { |hash| hash[:nickname]} negative sign doesn't work, neither .reverse
What is the best way to sort_by alphabetically the values of a specific line in an array of hash?
#compositionsProduct.sort_by { |hash| hash[:nickname] }.reverse works very well.

How to update multiple users with form in Rails?

I want to use form_for to create a form and update multiple users.
Let's say each user has :id and :name. I would like the POST parameters to be:
{
"users": [
{
"id": 1,
"name": "Bob"
},
{
"id": 2,
"name": "Leo"
}
......
]
}
The form looks like([] means input fields):
Users
1 [ Bob ]
2 [ Leo ]
3 [ ]
How does the form_for code looks like?
form_tag your_url, method: :post do |f|
#users.each do |user|
label_tag user.id
hidden_field_tag "users[][id]", user.id
text_field_tag "users[][first_name]", user.first_name
end
end
I think it will pass parameters as you want, but the hard thing is how to show detail error messages for each user

TypeError - no implicit conversion of String into Integer

Excuse me for the noob question.
I am using https://newsapi.org/ in my rails app and I am using httparty gem.
def news
#techcrunch = HTTParty.get('https://newsapi.org/v1/articles?source=techcrunch&apiKey=766c2f65e93c477451455xxxxxxxxxxx',
:headers =>{'Content-Type' => 'application/json'} )
respond_to :html, :json
end
news.html.erb
<% if (#techcrunch.nil? or #techcrunch== []) %>
<p> <h2>No news found.. Sorry</h2></p>
<% else %>
<% #techcrunch.each do |techcrunch| %>
<td><%= link_to(image_tag(techcrunch["urlToImage"], height: '100', width: '100'), techcrunch.articles["url"])%></td>
<td><%= link_to(techcrunch["title"], techcrunch["url"]) %></td>
<td><%= techcrunch["publishedAt"] %></td>
<% end %>
<% end %>
I am now getting an error
no implicit conversion of String into Integer
in the line
<td><%= link_to(image_tag(techcrunch["urlToImage"], height: '100', width: '100'), techcrunch.articles["url"])%></td>
I checked the API in postman and the response is as below
{
"status": "ok",
"source": "techcrunch",
"sortBy": "top",
"articles": [
{
"author": "Matthew Panzarino",
"title": "Apple Music’s first new personalized playlist wants you to Chill",
"description": "This week Apple is beginning to roll out the first new personalized playlist under Apple Music’s ‘For You’ section. The playlist, entitled ‘Chill’..",
"url": "https://techcrunch.com/2017/06/27/apple-musics-first-new-personalized-playlist-wants-you-to-chill/",
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2017/06/img_0021.jpg?w=764&h=400&crop=1",
"publishedAt": "2017-06-28T02:45:58Z"
},
{
"author": "Josh Constine",
"title": "Facebook now has 2 billion monthly users… and responsibility",
"description": "Thirteen years after launching and less than five years after hitting 1 billion, Facebook now has 2 billion monthly active users. If getting to 1 billion was..",
"url": "https://techcrunch.com/2017/06/27/facebook-2-billion-users/",
"urlToImage": "https://tctechcrunch2011.files.wordpress.com/2017/06/facebook-users-snapchat-twitter-youtube-whatsapp-instagram-wechat-qq.png?w=764&h=400&crop=1",
"publishedAt": "2017-06-27T17:06:05Z"
}
]
}
How can I display all the articles using news.html.erb?
Any help is Highly Appreciated.Thanks in Advance!
The problem is here:
techcrunch.articles["url"]
techcrunch["articles"] is an array. You might want to iterate through articles:
<% #techcrunch["articles"].each do |techcrunch| %>
and remove .articles:
techcrunch["url"]
from where it failed.
You should check the api response on your console to see what you're getting and go from there.
def new
...etc
puts #techcrunch
end
or even inside the view, before everything <%= #techcrunch %>
You're probably looping through a string and not an object, and the error comes from it being a string and when you call ["urlImage"] it should be an integer indicating an index and not a string ("urlImage"). You'll need to parse and organise the response first before iterating through it.
Also, you can just call:
if #techcrunch.blank?
instead of .nil? && == []

Rails - select_tag form helper is not working properly

I just recently started working in rails forms, and though I have scoured the api docs many times, I have not been able to figure out how to use it properly.
Basically, in my app I have a form to place a manual order (shipping). I would like there to be a select tag for specifying the state to be shipped to. I am working with an pre-existing SQLServer database, and the column I would want to display, and edit is :SHIPTOSTATE . However, when I go to edit an instance of an order, the form always shows "AL" and changing the state does not actually update the shipping state in my form. Can someone point out what I am doing wrong here?
The rest of my form is working beautifully, as the form is mostly text-fields at this point. The text-fields update just fine, but the select_tag is still troublesome.
Here is a snippet of the code in question:
<%= select_tag :SHIPTOSTATE, options_for_select(["AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "FL", "GA", "HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY"]) %>
Did you add :SHIPTOSTATE to permit method inside controller?
select_tag on it's own does not know which object you are attaching to. You need to provide a current value. You can do that with adding a second parameter to the options_for_select call.
options_for_select(["AL","AK"...], "Current State")
Then you have to explicitly look at the params[:SHIPTOSTATE] in your controller method.
You might also be using form_for. In that case you would want to use something like f.select and not use select_tag at all:
<%= form_for #your_object do |f| %>
# ...
<%= f.select :SHIPTOSTATE, ["AL","AK"...]
# ...
<%= f.submit %>
<% end %>
When you're dealing with a model, using the conventions in Rails, it's rare that you'd use the select_tag helper - you'd usually use the select helper, something like this:
= f.select :SHIPTOSTATE, %w[AL AK AZ AR ..etc]
If changing to using that helper doesn't work for you then you'll need to show us your controller, and perhaps your model schema, so we can see what else might be wrong here.

multiple records using the select_tag

Update: To clear up confusion: by multiple records I mean multiple individuals at once. Each voter would have their own select__tag, this is the reason I want to pass the ID as a hash.
I'm attempting to display multiple records, with each record displaying its own selection box. I would like to submit this form and pass a hash, having the Add.id function as the key of the hash, and the selection box option pass as the information in the hash. How could I fix my code? is this even possible with the select_tag method?
<%= form_tag yardsign_adds_path, :method => :post do %>
<%= select_tag "support_code[]",
options_for_select([[ "1 - Strong Supporter", add.id ],
[ "2 - Likely Voter" ],
[ "3 - Undecided" ],
[ "4 - Likely Opposed" ],
[ "5 - Strongly Opposed" ]]) %>
<%= submit_tag "Update" %>
<% end %>
Current terminal output:
Started POST "/adds/yardsign" for 127.0.0.1 at 2010-04-17 01:36:03
Processing by AddsController#yardsign as HTML
Parameters: {"commit"=>"Update", "authenticity_token"=>"VQ2jVfzHI7pB+87lQa9NWqvUK3zwJWiJE7CwAnIewiw=", "support_code"=>["1", "3 - Undecided", "3 - Undecided"]}
From the little i get ur question i assuming u want user will able to select more than one option from the select list refer following code (please ignore if you want something else )
<%= select_tag "support_code[]", :multiple=>true
options_for_select([[ "1 - Strong Supporter", add.id ],
[ "2 - Likely Voter" ],
[ "3 - Undecided" ],
[ "4 - Likely Opposed" ],
[ "5 - Strongly Opposed" ]]) %>

Resources