Rails helper method return NilClass - ruby-on-rails

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(' ') %>

Related

Rails: How to pass params of multiple checkbox to the model

i built this form that generate me some chebox with value like "U6", "U8" eccc
<%= form.label "Seleziona Categorie" %>
<% TeamCategory::NAMES.each do |category| %>
<%= check_box_tag 'categories_selected[]', category -%>
<% end %>
Now i have to pass the value of selected check_box to a method in my model.
Now is:
def create_tournament_team_categories
TeamCategory::NAMES.each do |name|
team_category = TeamCategory.where(name: name).first_or_create
self.tournament_team_categories << TournamentTeamCategory.create(team_category: team_category)
end
end
I would like to replace the TeamCategory::NAMES.each do with "selected check_box each do" and TeamCategory.where(name: name) with the value selected.
Thank you in advance
I am a newbie with Rails. What I see is that you took the part of the form to create the team, right?
For your code straight forward it could be:
<%= form.label "Seleziona Categorie" %>
<% TeamCategory::NAMES.each do |name| %> #you are looping through team category NAMES constant
<%= check_box_tag 'category_names_selected[]', name %>
<% end %>
Your form as is allows more than one category to be selected.
For the method:
def create_tournament_team_categories(category_names_selected)
category_names_selected.each do |name|
team_category = name
self.tournament_team_categories << TournamentTeamCategory.create(team_category: team_category)
end
end
you will probably use this method in your teams_controller.rb. In the controller, you should be able to retrieve from params a freshly created array of selected names with something along the lines with this.
#category_names_selected = params[:category_names_selected]
I do not know how complicated your app is so it might also be nested under ["team"][:category_names_selected] or ["team"]["category_names_selected"] in your params hash.
To see the exact structure of the params hash and adjust the equation above you can add for example require 'pry' at the top of your controller file and then but the binding.pry just after the part where your method is executed. When you restart the server and the app hits this part of the controller you should be able to see the exact structure of your params hash in the terminal.
You can then pass the array to the method that you can call in the controller. Do not forget to add :category_names_selected to the strong params in the controller. I hope this helps.
Controller on line 30
def create
#tournament = Tournament.new(tournament_params)
#tournament.sport_club = current_user.sport_club
#category_names_selected = params[:category_names_selected]
if #tournament.save
redirect_to tournaments_path, notice: 'Torneo creato con successo'
end
end
Method create_tournament_team_categories in the model
after_create :create_tournament_team_categories
def create_tournament_team_categories(category_names_selected)
#category_names_selected.each do |name|
team_category = name
self.tournament_team_categories << TournamentTeamCategory.create(team_category: team_category)
end
end

Ruby on Rails : Find record of an object without querying database

I want to know how to get a specific record from an object example
#user = User.all
In index.html.erb, I want to show only the record that in the 3rd order , I try, but this gives me all the records. :
<% #user.each do |u| %>
I found this :
<% #user.find{|b| b.id == 1}%>
<%= #service.full_name%>
But didn't work and I don't know how to use it right in index.html.erb
Also you can take array element directly in template. For reason – if you need all another users to
<div class="super-user">
<%= #users[3].name %>
</div>
<div class="other-users">
<% #users.each do |u| %>
Destroy Him!
<% end %>
</div>
If you don't need all another users, prefer to don't fetch them all. Use find or find_by methods e.g.
#user = User.find(4) # finds user by id=4
or
#user = User.find_by(name: 'user', admin: true) # finds by hash arguments
or even
# fetch direcly 3-th user from database
#user = User.order(:id).limit(1).offset(2).first
http://guides.rubyonrails.org/active_record_querying.html
http://ruby-doc.org/core-2.3.1/Array.html
You can also just write
#user = User.all.third
Boris is right though just returning all the records is a bad practice. It may not be noticeable at this point in time but as the amount of User records in your database grow this query will get proportionally slower. So the better option is
#user = User.third

Rails - when a row returns nil

I'm getting this error when loading my view that has a Model User that has no records in it. I simply want it to return "Unassigned" in the view if there is no record. Otherwise, display the first and last name of the User. Displaying User first and last name works as expected when a record exists.
I've messed around with many different combinations of this and can't see to get it to work.
Error:
undefined method `full_name' for nil:NilClass
In tickets.index.html.erb:
<% #tickets.each do |ticket| %>
<%= ticket.user.full_name %>
<% end %>
In ticket.rb Model
def full_name
if full_name.blank?
full_name = "Unassigned"
else
ticket.user.first_name + ' ' + ticket.user.last_name
end
end
The problem is that when you call ticket.user that might be nil, so you can't call anything on it. You have the right idea in making a method on your Ticket model to isolate this, but it's calling itself which will get an infinite loop, and also you're still calling the method on your user and not your ticket. Try this:
In your view:
<% #tickets.each do |ticket| %>
<%= ticket.full_name %>
<% end %>
In your ticket model:
def full_name
if user.nil?
return "Unassigned"
else
return user.full_name
end
end
And in your user model:
def full_name
return "#{first_name} #{last_name}"
end
I made the user model have its own method for this so it's further isolated (following OO practices).

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

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.

RoR scope issue

I have a users table. It contains a field "user_type".
I added the following scope stmts to the user.rb file:
scope :uemployee, where(:user_type => 'employee')
scope :uclient, where(:user_type => 'client')
scope :ucontractor, where(:user_type => 'contractor')
I created a view and I would like it to list he employees.
Here is the code I'm trying to use:
<% #users.uemployee.each do |user| %>
But, I get "undefined method `uemployee' for nil:NilClass"
What am I doing wrong?
Thanks
Looks like you wanted to do this:
<% User.uemployee.each do |user| %>
But this is considered to be a bad practice. You have to prepare you data in a controller and a view just cycles through it:
# in a controller's action
#users = User.uemployee
#in a view
<% #users.uemployee.each do |user| %>
But even this isn't the best approach. If you create the file views/users/_user.html.erb which shows the info about a particular user (current user will be available as a simple user variable, without the #) then you can simply write:
# in a view
<%= render #users %>
# remember, #users variable was set in your controller
then Rails will cycle through all the users "inside" the #users variable and show them one-by-one.
Your #users collection is nil

Resources