Rails loop in html erb - ruby-on-rails

How can I simplify the following lines:
<% if #campaign.previous_campaign.present? %>
<%= #campaign.previous_campaign.product_name %>
<% if #campaign.previous_campaign.previous_campaign.present? %>
<%= #campaign.previous_campaign.previous_campaign.product_name %>
<% end %>
<% end %>
I need to keep adding ".previous_campaign" until it is not present. So the next one in the above code would be:
<%= #campaign.previous_campaign.previous_campaign.previous_campaign.product_name %>
etc etc.

Something like this:
<% campaign = #campaign %>
<% while campaign.previous_campaign.present? %>
<% campaign = campaign.previous_campaign %>
<%= campaign.product_name %>
<% end %>
The code may need some debugging, but I guess the idea is clear

You could do something like this:
<% for c in #campaign do %>
<% if c.previous_campaign.present? %>
<%= c.previous_campaign.product_name %>
<% end %>
<% end %>

Related

Pushing a Locale Variable to Partial in Rails 4.2

I have a partial that pulls the list of games someone has in their Steam Library
<h1><%= header %></h1>
<% player = SteamWebApi::Player.new(steamId)
owned_games = player.owned_games(include_appinfo: true)%>
<% owned_games.each do |game| %>
<%= game['playtime_2weeks'] %>
<% if game['img_icon_url'].blank? %>
<%= image_tag 'http://www.readyicons.com/IconSets/Sky_Light_(Basic)/32x32-no.png' %>
<% else %>
<%= image_tag "http://media.steampowered.com/steamcommunity/public/images/apps/#{game['appid']}/#{game['img_icon_url']}.jpg" %>
<% end %>
<%= game['name'] %><br>
<% end %>
And it's base view feeds off of current_user.player_steam_id - A field in SQL.
Originally this was nice to show only your present games, but I want to do a few things with it.
A) When you check someones profile, you see their list.
B) You can search with a users ID, to pull the query results.
My initial issue is using (XXXXXX is actually a number, so I don't stringify it(Do I?)
<%= render :partial => 'game_list', :locals => {:header => "Welcome to His Page!", :steamId => XXXXXXXXXX } %>
And the "Welcome to His Page!" is getting passed, but I'm having a lot of issues getting :steamId to render.
In the partial view I've tried rendering it with <%= steamId %> <% steamId %> and :steamId
The current and :steamId are the only two that don't break the page, but it doesn't render anything. I'm fairly new to this so trying to figure it out, but I've found numerous posts that say I'm doing it right.
I'm welcome to any input.
Also - Since I plan to use this widely, should I look into making it a Controller? Or would the partial suffice?
(P.S. I'm typically a Node guy, so I tried debug+console.log(steamId) a lot to see how it's rendering, but I didn't get results in console.log, and debug didn't do anything. How do you normally debug something like this in RoR?
Thanks for any input!
EDIT:
Additional Info:
The issue with this was partially in the partial.
<h1><%= header %></h1>
<% player = SteamWebApi::Player.new(steamId)
owned_games = player.owned_games(include_appinfo: true)%>
<% owned_games.each do |game| %>
<%= game['playtime_2weeks'] %>
<% if game['img_icon_url'].blank? %>
<%= image_tag 'http://www.readyicons.com/IconSets/Sky_Light_(Basic)/32x32-no.png' %>
<% else %>
<%= image_tag "http://media.steampowered.com/steamcommunity/public/images/apps/#{game['appid']}/#{game['img_icon_url']}.jpg" %>
<% end %>
<%= game['name'] %><br>
<% end %>
By modifying it to owned_games definition, and player definition are on separate lines, it resolved successfully. This was just a not-reviewing-what-I-copied/pasted fail on my part.
Resolved code:
<h1><%= header %></h1>
<% puts steamId %>
<% player = SteamWebApi::Player.new(steamId) %>
<% owned_games = player.owned_games(include_appinfo: true)%>
This is my steam ID <%= steamId %>
<% owned_games.each do |game| %>
<%= game['playtime_2weeks'] %>
<% if game['img_icon_url'].blank? %>
<%= image_tag 'http://www.readyicons.com/IconSets/Sky_Light_(Basic)/32x32-no.png' %>
<% else %>
<%= image_tag "http://media.steampowered.com/steamcommunity/public/images/apps/#{game['appid']}/#{game['img_icon_url']}.jpg" %>
<% end %>
<%= game['name'] %><br>
<% end %>
However, I am only able to have it render if it pulls the player_steam_id from the DB.
So for instance if I have
:steamId => 76561198017108025
It won't work, but if I have
:steamId => User.player_steam_id it does work.
(Again, 'User' has a column in SQL that stores their player_steam_id)
I want to be able to call this on the 'Submit' of a search button, which is why I'm trying to see how to get the render to work with a specific number.
Why could that be the case? I have tried logging steamId with the view, and I see it being passed through as a normal integer. My only logical assumption is that the view loads, calls the API with 'steamId' THEN renders steamId but I'm just guessing?
Update Trial-n-Error
So I tried out using something like
<h1><%= header %></h1>
<% appCall = steamId %>
<% player = SteamWebApi::Player.new(appCall) %>
<% owned_games = player.owned_games(include_appinfo: true)%>
<%= appCall %>
<%= owned_games.success %>
<% owned_games.each do |game| %>
<%= game['playtime_2weeks'] %>
<% if game['img_icon_url'].blank? %>
<%= image_tag 'http://www.readyicons.com/IconSets/Sky_Light_(Basic)/32x32-no.png' %>
<% else %>
<%= image_tag "http://media.steampowered.com/steamcommunity/public/images/apps/#{game['appid']}/#{game['img_icon_url']}.jpg" %>
<% end %>
<%= game['name'] %><br>
<% end %>
I am able to get an output with the puts, and also be using the 'player.success' function of the API. Which returns "True", and puts steamId and app both render out the ID.
I also tested printing out the entire array before the 'for', and did notice it gives me all of the data.
true #<OpenStruct count=31, games=[{"appid"=>300, "name"=>"Day of Defeat: Source", "playtime_forever"=>48,
So the issue lies in the 'for' section of the partial, I'm thinking. Would I need to run the for in the main document, and feed it data from the partial? That seems of...
Is game_list a partial or is it a regular view? A partial will begin with an underscore as the file name. _game_list.html.erb
Try this
<%= render 'game_list', :header => "Welcome to His Page!", :steamId => XXXXXXXXXX %>
Then you can render steam ID like this <%= steamId %> inside of the partial.
Edit:
If you are not referencing steamId in direct output area you don't need to wrap it in <%= %>
Try SteamWebApi::Player.‌​new(steamId) instead of SteamWebApi::Player.‌​new(<%= steamId %>)
Another Edit
Try this
<h1><%= header %></h1>
<% player = SteamWebApi::Player.new(steamId)
owned_games = player.owned_games(include_appinfo: true)%>
This is my steam ID <%= steamId %>
<% owned_games.each do |game| %>
<%= game['playtime_2weeks'] %>
<% if game['img_icon_url'].blank? %>
<%= image_tag 'http://www.readyicons.com/IconSets/Sky_Light_(Basic)/32x32-no.png' %>
<% else %>
<%= image_tag "http://media.steampowered.com/steamcommunity/public/images/apps/#{game['appid']}/#{game['img_icon_url']}.jpg" %>
<% end %>
<%= game['name'] %><br>
<% end %>
I added
This is my steam ID <%= steamId %>
The issue ended up being the Partial I had used as a template. It never modified the array of 'games' into 'game', so when it was iterating through the games 'each' it never returned any results.
My final partial works as intended.
<h1><%= header %></h1>
<% player = SteamWebApi::Player.new(steamId) %>
<% owned_games = player.owned_games(include_appinfo: true)%>
<% game = owned_games.games %>
<% games.each do |game| %>
<%= game['playtime_2weeks'] %>
<% if game['img_icon_url'].blank? %>
<%= image_tag 'http://www.readyicons.com/IconSets/Sky_Light_(Basic)/32x32-no.png' %>
<% else %>
<%= image_tag "http://media.steampowered.com/steamcommunity/public/images/apps/#{game['appid']}/#{game['img_icon_url']}.jpg" %>
<% end %>
<%= game['name'] %><br>
<% end %>
Once I added the additional modifier, it was able to render the list successfully.

conditional in users/show page to display info or not based users having created it

This is the error I get:
Showing /home/ubuntu/workspace/UMUV/app/views/users/show.html.erb where line #6 >>raised:
undefined method `name' for nil:NilClass
This is my conditional in users/show:
<% if #profile_info.present? %>
<%= #profile_info.region.name %>
<% else %>
<%= #user.email%>
<% end %>
This is in the users/controller:
def show
#user = User.find(params[:id])
#profile_info = Profile.find_or_initialize_by(user_id: params[:id])
end
I basically want to know how to not have an error when i visit a user's profile page and the user hasn't updated their profile yet. Showing the page is working fine if i update the user's profile through "edit page" manually.
Please help with the conditional. I also have a feeling i can create method in user.rb or users/controller, but really dont know how to implement this conditional to do what i want it to.
Thank you
In your show page you can replace this :
<% if #profile_info.present? %>
<%= #profile_info.region.name %>
<% else %>
<%= #user.email%>
<% end %>
with this:
<% if #profile_info.present? %>
<%= #profile_info.region.try(:name) %>
<% else %>
<%= #user.try(:email)%>
<% end %>
and also go through this post: http://everydayrails.com/2011/04/28/rails-try-method.html
Well you can always test an initalized object vs a saved object using new_record? -- which would make your above view look more like:
<% if #profile_info.new_record? %>
<%= #user.email%>
<% else %>
<%= #profile_info.region.name %>
<% end %>
also you might be able to take advantage of try on part of your page, which fails gracefully if an attribute doesn't exist, like
#profile_info.region.try(:name)
Since your error is with the name #profile_info.region.name not being present you could change your conditional to:
<% if #profile_info.region.name.present? %>
<%= #profile_info.region.name %>
<% else %>
<%= #user.email%>
<% end %>
Or if you really want to test #profile_info.present? you could nest conditionals like this:
<% if #profile_info.present? %>
<% if #profile_info.region.name.present? %>
<%= #profile_info.region.name %>
<% end %>
<% else %>
<%= #user.email%>
<% end %>
I hope that helps!

Unable to get the value of a variable inside Rails erb tags

I want to understand the erb usage. In the below code I am unable to figure out how to get the value of (group.id) in the if clause using the erb tags.
This probably has a very basic solution but I am unable to get proper answers.
The below code gives me syntax error.
<% current_user.favorite_groups.to_a.each do |group| %>
<%= if (group.id).newfavorite_texts.exists?(id: text.id) %>
<%= group.name %>
<%= link_to # do something %>
<% else %>
<%= group.name %>
<%= link_to # do something else %>
<% end %>
<% end %>
Thanks in advance.
You should be get going with the below code
<% current_user.favorite_groups.to_a.each do |group| %>
<% if group.newfavorite_texts.exists?(id: text.id) %>
<%= group.name %>
<%= link_to # do something %>
<% else %>
<%= group.name %>
<%= link_to # do something else %>
<% end %>
<% end %>

Using to_sentence

I'm a newbie...
I know how to use "to_sentence" when I have something like:
<%= #blah.collect {|b| b.name}.to_sentence %>
but what if I have a more complex block like:
<% skill.position.each do |position| %>
<%= position.company.name %>
<% if position.salary? %>
<span><%= position.salary %></span>
<% end %>
<% end %>
The desired output is:
Microsoft, Google 2000, and Yahoo.
Couldn't you just collect it without .each?
<%= skill.positions.collect{ |p| "#{p.company.name}#{position.salary? ? '<span>#{position.salary}</span>' : nil}" }.to_sentence %>
That should work for you...
You could also do this:
<%= skill.position.each do |position| %>
<% position.company.name %>
<% if position.salary? %>
<span><% position.salary %></span>
<% end %>
<% end.to_sentence %>
The to_sentence methods works on Arrays. The reason that it works on your first example...
<%= #blah.collect {|b| b.name}.to_sentence %>
... is because the collect method returns an Array. The each method in your second example will also work because each also returns an Array. So, this will work:
<% blah.each do |b| %>
...
<% end.to_sentence %>

"Not Available" Rails

Dear All,
When I use a table from database, if data is not available in table. I will use if and else conditions like
<% if #tables.blank? %>
<p> Not available</p>
<% else %>
blaaa blaa
<% end %>
It works fine. Now I need to apply the same thing for connected tables. If data is available in first table tables and not available in benches. How I can apply??
I tried like this
<% #tables.each do |table| %>
<% if table.benches.blank? %>
<p> Not available</p>
<% else %>
blaaa blaa
<% end %>
<% end %>
... But its not working. Kindly give me suggestions.
I'm not quite sure what you want, but maybe this will help you.
<% if #tables.blank? %>
<p> Not available</p>
<% else %>
<% #tables.each do |table| %>
<% if table.benches.blank? %>
<p> Not available</p>
<% else %>
blaaa blaa
<% end %>
<% end %>
<% end %>
Try using #empty?.
<% #tables.each do |table| %>
<% if table.benches.empty? %>
<p> Not available</p>
<% else %>
blaaa blaa
<% end %>
<% end %>
What happens if you try this:
<% unless table.benches.exists? %>
<p> Not available</p>
<% else %>
blaaa blaa
<% end %>
if/else must output one or the other... make sure you check your HTML source code (not just browser view) to see if the output isn't hiding somewhere inside a tag.
Dear All, Its working... when i apply like this...
<% if #tables.blank? %>
<p> Not available</p>
<% else %>
<% #tables.each do |table| %>
<% table.benches.each do |bench| %>
<% if bench.column.blank? %>
<p> Not available</p>
<% else %>
blaaa blaa
<% end %>
<% end %>
<% end %>
<% end %>
Thank you for everyone who participated in this Question.

Resources