I've the following code in a .html.erb file which is called from show.html.erb.
<%-
platforms = ["a", "b", "c", "d"]
%>
<%- platforms.each do |platform| -%>
<%- if user.send("#{platform}_rate") -%>
<%= render "users/credentials/#{platform}", user: user %>
<%- else -%>
Not Connected
<%- end -%>
Unfortunately b_rate doesn't exist and is breaking with the following error:
undefined method `b_rate' for #<User:0x00007hgh9b842ce0>
How can I check if each _rate exists before using send method without getting messy with the code?
I went with this, suggested by Dave. Does the job for me. Thanks.
platforms = ["a", "b", "c", "d"]
%>
<%- platforms.each do |platform| -%>
<%- if user.respond_to?("#{platform}_rate") || user.respond_to?("#{platform}_rates") -%>
<%= render "users/credentials/#{platform}", user: user %>
<%- else -%>
Not Connected
<%- end -%>
Related
I have this code:
<% #lookup_coins.each do |x| %>
<% if #symbol == '' %>
<%= 'Sorry, but you forgot to write something, LOL'%>
<% elsif #symbol == x %>
<%= x["symbol"]%> <br/> <%= x["name"]%>: <%= number_to_currency(x['quote']['USD']['price'].round(2) , :unit => "$ ") %> <br/> <%= x["cmc_rank"]%> <br/>
<% else 'Sorry, there was a mistake, try again'%>
<% end %>
The info looks like this:
[{"id"=>1, "name"=>"Bitcoin", "symbol"=>"BTC", "slug"=>"bitcoin", "num_market_pairs"=>9713, "date_added"=>"2013-04-28T00:00:00.000Z", "tags"=>["mineable", "pow", "sha-256", "store-of-value", "state-channels", "coinbase-ventures-portfolio", "three-arrows-capital-portfolio", "polychain-capital-portfolio"], "max_supply"=>21000000, "circulating_supply"=>18633612, "total_supply"=>18633612, "platform"=>nil, "cmc_rank"=>1, "last_updated"=>"2021-02-20T07:45:02.000Z", "quote"=>{"USD"=>{"price"=>55541.51774356704, ...
I am not sure how to do it in the correct way
It looks like you're failing to match to the actual symbol value, but instead are expecting #symbol to perfectly match a Hash, which it won't.
Secondly, you're also printing that "forgot to write something" message each time through the loop which is wrong. You can get rid of the loop, just use find to locate the entry right away, and then as a bonus you can more easily detect a "missed" condition.
Just see if you can find a matching entry, otherwise display the message.
The fix looks like:
<%- if #symbol.blank? -%>
Sorry, but you forgot to write something.
<%- else -%>
<%- found = #lookup_coins.find { |c| c['symbol'] == #symbol } -%>
<%- if (found) -%>
<%= found["symbol"]%> <br/> <%= found["name"]%>:
<%= number_to_currency(found['quote']['USD']['price'].round(2), :unit => "$ ") %>
<br/>
<%= found["cmc_rank"]%> <br/>
<%- else -%>
Sorry, there was a mistake, try again
<%- end -%>
<%- end -%>
Using #symbol.blank? here which is more forgiving than == '' as it will also reject a bunch of spaces and/or tabs.
Tip: Don't use <%= '...' %> Instead just put the text there as-is. The default is to echo it.
<% if #symbol %>
<%#resultant_symbol = #lookup_coins['data'].select {|lookup_coin| lookup_coin["symbol"] == #symbol }%>
<%if #resultant_symbol.present?%>
<% x = #resultant_symbol.first %>
<%= x["symbol"]%> <br/> <%= x["name"]%>: <%= number_to_currency(x['quote']['USD']['price'].round(2) , :unit => "$ ") %> <br/> <%= x["cmc_rank"]%> <br/>
<%else%>
<%= #symbol = 'Sorry, there was a mistake, try again'%>
<%end%>
My code is working in console but not in App
➜ Meet-and-Eat git:(master) ✗ rails c
Running via Spring preloader in process 15789
Loading development environment (Rails 5.2.2)
2.5.3 :001 > i = ["10 Palmerston Street", "DERBY"]
=> ["10 Palmerston Street", "DERBY"]
2.5.3 :002 > result = Geocoder.search("#{i[0]}, #{i[1]}").first.coordinates
=> [52.9063415, -1.4937474]
My code :
<% #places = [] %>
<% #placesCoordinations = [] %>
<% #information.each do |i| %>
<% #places.push([i.address1, i.town, i.postcode, information_path(i)]) %>
<% end %>
<% #places.each do |i| %>
<% result = Geocoder.search("#{i[0]}, #{i[1]}").first.coordinates %>
<% #placesCoordinations.push(result) %>
<% end %>
Error :
NoMethodError in Information#full_map_adresses.
Showing /Users/mateuszstacel/Desktop/Meet-and-Eat/app/views/information/full_map_adresses.html.erb where line #10 raised:
undefined method `coordinates' for nil:NilClass
<% #places.each do |i| %>
<% result = Geocoder.search("#{i[0]}, #{i[1]}").first.coordinates%> //this line is breaking my app
<% #placesCoordinations.push(result) %>
<% end %>
But if I use only single location or postcode or street address that work but i need to use both of them to be more precision.
<% #places = [] %>
<% #placesCoordinations = [] %>
<% #information.each do |i| %>
<% #places.push([i.address1, i.town, i.postcode, information_path(i)]) %>
<% end %>
<% #places.each do |i| %>
<% result = Geocoder.search("#{i[2]}").first.coordinates %>
<% #placesCoordinations.push(result) %>
<% end %>
The error message undefined methodcoordinates' for nil:NilClassindicates that theGeocoder.search("#{i[0]}, #{i[1]}")itself is successful, butGeocoder.search("#{i[0]}, #{i[1]}").firstsimply returnsnil`.
It seems like your #information array contains at least one address that cannot be resolved. There might be many reasons: Perhaps there is just a typo in the address or it is a very small village or an address in a country which is not supported by the service you are using.
Tip to debug: Change your code to show what it passes to the method and if there were any results. Something like this might help:
<% #places.each do |i| %>
Address string: <%= "#{i[0]}, #{i[1]}" %>
<% result = Geocoder.search("#{i[0]}, #{i[1]}").first %>
Result: <%= result.present? %>
<% #placesCoordinations.push(result.coordinates) if result.present? %>
<% end %>
Furthermore: I suggest moving code like this to a model, the controller or a helper. It feels like this doesn't belong in an ERB view.
Finally that work !
Inside of the model :
class Information < ApplicationRecord
geocoded_by :address
after_validation :geocode
def address
[address1, address2, town, postcode].compact.join(", ")
end
end
then in terminal run command :
rake geocode:all CLASS=Information SLEEP=0.25 BATCH=100
I have the following entry in an erb template:
# Lorem Ipsum...
<% unless #foo['bar'] == nil %>
<% #foo['bar'].each do |property, value| %>
<%= "zaz.#{property} #{value}" %>
<% end %>
<% end %>
That is parsed to:
# Lorem Ipsum...
zaz.property value
How can I remove the leading spaces so that lines are not indented in the resolved template?
I would like to avoid using something like:
# Lorem Ipsum...
<% unless #foo['bar'] == nil %>
<% #foo['bar'].each do |property, value| %>
<%= "zaz.#{property} #{value}" %>
<% end %>
<% end %>
The only solution I can offer is hackish adding <%- 'whatever here' %> before the <%= %> entry:
<% [1,2,3].each do |f| %>
<%- 1 %><%= f %>
<% end %>
it outputs in irb
irb(main):018:0> ERB.new(File.read('f.txt'), nil, '-').result
=> "\n1\n\n2\n\n3\n\n"
Rails doc claims, that default value for ERB trim_mode is -
http://edgeguides.rubyonrails.org/configuring.html#configuring-action-view
And according to https://www.systutorials.com/docs/linux/man/1-erb/ ERB should remove spaces before <%- when - mode is enabled.
You could indent the code instead of the ERB tags:
# Lorem Ipsum...
<% unless #foo['bar'] == nil %>
<% #foo['bar'].each do |property, value| %>
<%= "zaz.#{property} #{value}" %>
<% end %>
<% end %>
If you're controlling the string passed to ERB.new, then you can make yourself a new tag to use.
Given a template in a file:
<%~ 'hello' %>
<%~ 'world' %>
<%~ '!' %>
Do:
string = File.read(file_path).gsub('<%~', '<%-%><%=')
print ERB.new(string, trim_mode: '-').result
And get:
hello
world
!
I'd love it if ERB would include this tag itself, but until then I'm doing it myself.
I have the following code:
#items = QuestionGroup.search(params[:search]).limit(50)
This returns an ActiveRecord relation. In the view I want to iterate through it so I use:
<% if #items.present? %>
<%= #items.each do |r| %>
<%= div_for r do %>
<div><%= r.subject %></div>
<% end %>
<% end %>
<% end %>
This does print r.subject to the view but it then follows it with the entire relation. e.g.
the pipe
[#<QuestionGroup id: **, subject: "the pipe", created_at: "*******", updated_at: "******"]
Why is this and how can I fix it?
Problem is here:
<%= #items.each do |r| %>
This line of code iterates over each of the relations and due to the '=' you output its content. Change it to:
<% #items.each do |r| %>
and you are good to go!
I'm sort of new to Ruby on Rails and have been learning just fine, but have seem to run into a problem that I can't seem to solve.
Running Rails 3.0.9 & Ruby 1.9.2
I'm running the following statement in my View:
<%= #events.each do |f| %>
<%= f.name %><%= link_to "View", event_path(f) %><br/><hr/>
<% end %>
And this in my controller:
class AdminController < ApplicationController
def flyers
#events = Event.all
end
end
This goes through each of the records and outputs the appropriate name, but the problem is that at the end it displays all of the information for all of the records like so:
[#<User id: 1, username: "test account", email: "test#gmail.com", password_hash: "$2a$10$Rxwgy.0ZEOb0lMGEIliPBeB/jPSp8roeKdbMvXcLi32R...", password_salt: "$2a$10$Rxwgy.0ZEOb0lMGEIliPBe", created_at: 2111359287.2303703, updated_at: 2111359287.2303703, isadmin: true>]
I'm new to this site, so I'm not sure if you need any more details, but any help is appreciated, after all, I'm still learning.
Thanks in advance.
You should be using <%, not <%= for your .each line, so
<%= #events.each do |f| %>
should be
<% #events.each do |f| %>
.each returns the entire array at the end once it is finished the loop.
<%= ... %> prints out the value of the statment, which is the value returned by .each
<% ... %> does not. So you want:
<% #events.each do |f| %>
<%= f.name %><%= link_to "View", event_path(f) %><br/><hr/>
<% end %>