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 %>
Related
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'm new to Ruby and Rails. I've been trying to get a view of all users to work and am not sure what I'm doing wrong.
I have a view with:
<% provide(:title, "View all Users") %>
<h1>Users#viewall</h1>
<p>Find me in app/views/users/viewall.html.erb</p>
<%
#users = User.all
#users.each do |user|
user.name
end
%>
The output of this is a list of objects in the database, with all the object's data. When I want to target (for example) just the name, it doesn't work.
[#<User id: 1, name: "user name", email: "mail#mail.com", created_at: "2016-08-03 15:40:41", updated_at: "2016-08-03 15:40:41", password_digest: "$2a$10$KmWWK86H/dj.HAp9zcHOUOCbph1rawIer41kyH4dIrV...">]
What am I missing here? I'm not even really sure what to google as I don't know what the loop is spitting out.
You are not displaying the data to the user.
In your controller method, is where you should add
#users = User.all
And in your view
<% #users.each do |user| %>
<h1><%= user.name %></h1>
<% end %>
<% %>: These brackets are used to evaluate an expression
<%= %>: These brackets evaluate an expression and render the output
You need to output the information. So in ERB when you have a tag like:
<% i = 4 %>
That executes code. When you have:
<%= "hi" %>
That outputs the return value. So what you actually want is this:
<% User.all.each do |user| %>
<%= user.name %>
<% end %>
What you should do with the users though, is setup an instance variable in your controller:
def viewall
#users = User.all
end
Then use it in your view:
<% #users.each do |user| %>
<%= user.name %>
<% end %>
Just better to keep SQL calls and a lot of logic out of your views. Leverage the controllers, models and helpers to do that.
Been trying to set up a regular blog in Ruby on Rails, and finally got the comment system to work within a post. However, when I loop through each comment and try to output the comment's title it displays this,
awef [#<Comment id: 6, title: "awef", link: nil, campaign_id: 5, user_id: 1, created_at: "2015-09-24 09:46:43", updated_at: "2015-09-24 09:46:43">]
Instead of just the title. How can I fix this?
The loop in your view should be something like this:
<% #blog.comments.each do |f| %>
<%= f.title %>
<% end %>
Please check you are using the right angular parenthesis (<%= %>) and not placing p puts or inspect commands inside them.
Edit:
Now that you show use the code, the problem is in the first angular parenthesis: should be <% not <%=. The first is for the logic, the latter to output erb code.
<% #blog.comments.each do |f| %> # remove "="
<%= f.title %>
<% end %>
<% ... %>: Executes the ruby code within the brackets
<%= ...%>: Executes the ruby code and show the executing result in webpage
Classic mistake, it's because you're using <%= ERB output tags for the .each loop. You can view more information on how to write correct ERB here.
You need to replace your <%= output tags with standard ERB tags <%:
<% #blog.comments.each do |f| %>
I was stung by that one myself when I was starting out.
The problem you have is probably the = in your each statement.
Try to use this:
<% #blog.comments.each do |f| %>
<%= f.title %>
<% end %>
Notice the removed = at <% #blog.comments.each do |f| %>
The reason is as the <%= %> always prints while <% %> only executes the code.
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 have this view
...code....
<% #feeds.each do |feed| %>
<%= check_box_tag(feed.name) %>
<%= label_tag(feed.name) %>
<% end %>
...code....
The Feed model looks like this
Feed(id: integer, name: string, description: string, url: string, created_at: datetime, updated_at: datetime, day_selector: string, special_selector: string)
and the submission comes into the params hash like this
{"utf8"=>"✓",
"authenticity_token"=>"WVbxZckIJCA0dXqPZGnSXJi7yrDN3Ssttv7dnJZOfBY=",
"email"=>"",
"phone_number"=>"",
"Squeaky Beaker"=>"1",
"Commonwealth Cambridge"=>"1",
"commit"=>"GO",
"action"=>"create",
"controller"=>"subscriptions"}
I want the params hash to look this this
{:feeds => {'Squeaky Beaker' => 1, 'Commonwealth Cambridge' => 1}}
or just simply
[{'Squeaky Beaker' => 1, 'Commonwealth Cambridge' => 1}]
How can I customize my view to have the params hash look the way I want?
untested, but you could try...
<ul>
<% #feeds.each do |feed| %>
<li>
<%= check_box_tag 'feeds[]', (feed.name => 1) -%>
<%= h feed.name -%>
</li>
<% end %>
</ul>
I'm not sure the => 1 has value to your application, so the more traditional approach would be
<%= check_box_tag 'feeds[]', feed.name -%>
interpreted from the documentation at http://apidock.com/rails/ActionView/Helpers/FormTagHelper/check_box_tag
Check Box
To further SteveTurczyn's answer, what you're basically doing right now is outputting two checkboxes (completely different to each other), which will both hold a value of "1" (checked):
<% #feeds.each do |feed| %>
<%= check_box_tag(feed.name) #-> feed.name will be different each time %>
<%= label_tag(feed.name) %>
<% end %>
You'll need to give the check boxes the same name, as to give Rails the ability to discern their values being different. And secondly, you'll need to ensure you have the correct vales / options for the boxes too:
<% #feeds.each do |feed| %>
<%= check_box_tag "feeds[]", feed.name %>
<% end %>
This will pass the parameters as follows:
["checked_value_1", "checked_value_2"]
If you use the names of the feeds, it will give you:
["Feed1", "Feed2"] #-> names
["5", "6", "7" ] #-> ids