How do I get rid of #<User:0x1095e07b8> after calling User.each? - ruby-on-rails

After looping through a User model in rails and displaying some columns, at the end of the view I get:
#<User:0x1095e07b8>#<User:0x1095dfed0>#<User:0x1095de080>
Any ideas on how to get rid of this? Also what does it mean?

You are probably using this for your loop:
<%= User.all.each do |user| %>
The equals sign will print the output of that function to the page. Drop the equals to omit the output:
<% User.all.each do |user| %>
The looping will still occur, but the output won't hit the view.

Related

Rails helper method return NilClass

I have this code in User#index view:
<%= User.find_each do |user| %>
<%= user.name %>
<% end %>
which returns the user names:
user1 user2 user3 ...
Then I move this code to the UserHelper:
module UserHelper
def get_users
User.find_each do |user|
user.name
end
end
end
And call it from the User#index view with:
<%= get_users %>
The problem is that this is not returning any user. If I use <%= get_users.class %> it outputs NilClass. Why is the helper method not returning the user names?
Your helper method implicitly returns the result of calling find_each, which is different than returning a collection of user names.
Think of it like running 5.times { |n| puts n }: what's the value of that? Not "0 1 2 3 4", but "5", because times returns what it was called on, not what's run in its block.
Your original code, by the way, returns the exact same thing--you are relying on a side effect inside the find_each block, i.e., appending user.name to the response.
If you want to return a collection of the users' names you'd want to map/etc. and grab each user's name. Or, IIRC, you can do a find and a pluck so you only get back the users' names instead of all user fields.
You can use as below also,
<%= User.all.map(&:name).join(' ') %>

Ruby on Rails each iteration error when one record

I am stuck on what seems should have a very simple solution, but I can not find anything that will work! I am iterating results from a table on the index page (which returns a list of states). This works without any problems when multiple records are returned. However, when a single record is returned, I get an error: undefined method 'each' for #
I know it is causing the error when only one record is returned, but I can not find any documentation on how to handle this, especially in the case that 1 or 0 records could be returned.
Code in controller:
#states = State.find(params[:id])
Code in index page:
<ul>
<% #states.each do |state| %>
<li>
<%= state.state_name %>
</li>
<% end %>
</ul>
Because you're using find, when you send multiple ids in the params, multiple records are matched; when you send a single id, a single instance is returned.
To ensure that each time, you get an ActiveRecord::Relation object that you can call each on, change your controller code to the following:
#states = State.where(id: params[:id]) # index action
You mentioned that it is the index view, so the above change should solve your problem.
If it's the show view, then you need to stick with find and change your view to display only one state.
You need to check if it responds to .each, which is the prime given for knowing if something implements the enumerable module.
if #states.respond_to?(:each)
# iteration goes here
else
# single handling goes here
Ofcourse you can also use the .where option in your query which returns always a collection
#states = State.where(id: params[:id])
Scenario 1:-
When record is queried in controller as:
#states = State.find(params[:id])
Then in view it should be like that:
<p><%= #states.state_name %></p>
Scenario 2:-
When record is queried in controller as:
#states = State.all
Then in view it should be like that:
<ul>
<% #states.each do |state| %>
<li>
<%= state.state_name %>
</li>
<% end %>
</ul>
Note:- In first scenario it is only one object but in second scenario it is a collection of object or a array of object. And only array are iterated.

Rails shows rows from model, which aren't created

I have this part of code:
<% current_user.meta_accounts.each do |meta_account| %>
<%= content_tag(:li, link_to(meta_account.name, 'javascript:void(0)')) %>
<% end %>
So, I want Rails to show all my MetaAccounts in list, but I get this:
<li>Wallet</li>
<li>Credit card</li>
<li>Debit card</li>
<li>Debts</li>
<li>javascript:void(0)</li> #This is the problem
So, it also shows me MetaAccount, which isn't created yet.
In my MetaAccounts table I have this. I'm using Postgres.
So, it also shows me the last row, where row_number is *. I don't know why, and how to avoid this.
Thanks for any help!
Try:
<% current_user.meta_accounts.select(&:persisted?).each do |meta_account| %>
<%= content_tag(:li, link_to(meta_account.name, 'javascript:void(0)')) %>
<% end %>
The * row you see in PostgreSQL is not an actual record, it's just a quick way to create new records. If you want to be sure, run the following query:
SELECT COUNT(*) FROM MetaAccounts WHERE user_id=1
It will return 4.
I think the problem comes from an unsaved MetaAccount object in current_user.meta_accounts. This could be the case for instance in a form, where you build an empty object bound to the form. Make sure you don't have a call to current_user.meta_accounts.build(...).
If so, you can simply skip in your each loop all MetaAccount objects with a blank name.

Get distinct values from table

I am trying to get distinct value from this controller. But I am not sure how to succeed.
Here the controller I have try this
#count = Present.where('event_id > ?', params[:id]).uniq.pluck(:customer_id)
But when I try to do this in my view
<% #count.each do | co | %>
<%= co.customer_id %>
<% end %>
I keep having this issues
Cannot visit Arel::Nodes::Distinct
I want to be able to preserve all Present Objects with the event_id equal to the id, but also being able to select only the one with distinct customer_id.
Update: after restarting the server i get the following error
undefined method `customer_id' for 1:Fixnum
Maybe you need to restart your rails server: https://github.com/rails/rails/issues/7399
Previous similar SO question
Update:
From the docs: When using pluck, "The values has same data type as column"
Change loop to:
<% #count.each %> do |i|
<%= i %>
<% end %>

block always returns true

Will always return true and erase the entire array
<% users.delete_if do |user| %>
<% false %>
<% end %>
On the other hand
<%
users.delete_if do |user|
false
end
%>
works and does not delete the array.
Can i somehow use the delete_if statement in my view and still be able to insert html?
Thanks
You shouldn't be modifying data at all in your views -- do this in your controller or model instead. Use views only to reflect the current state of your database, not change it.
If you then use the second version of your code in either of those places, this problem will disappear.
Ignoring the side-effect-in-a-view aspect, here is why the block "returns" a value: there is a generated print statement as part of the ERB template generated code between the "%>" and the "<% end". Any value left behind by this generated code will be used as the final statement / expression in the block, and thus its value.
I think, and I would have to test it if you use "yield" in the first form, it will work.
<% users.delete_if do |user| %>
<% yield false %>
<% end %>
But, as the first poster says, you shouldn't change data from a view.

Resources