Active record is not display table - ruby-on-rails

As working on the Active Record as i have work on different function for active reocrd like Avg, sum and count as it display working fine and also Chart,
but one things is baffle me and i still cannot get it working and it should be working fine, as i cannot get display all data list table like
<table id="dttb" class="table table-hover">
<thead>
<tr>
<th> full name </th>
</tr>
</thead>
<tbody>
<tbody>
<% #user.each do |user| %>
<tr>
<td><%= user.fullname %></td>
</tr>
<% end %>
</tbody>
</tbody>
</table>
as it should be working as the error is kept displayed
undefined method `each' for nil:NilClass
as I look up information and most of them are mention .each do, seems I am doing wrong as I have used
<%= User.count(:user) %>
and
<%= column_chart User.group(:provider).count(:user) %>
and it seems working fine as query function.
so I tried again with find_each
<% User.find_each do |user| %>
<tr>
<td><%= puts user.fullname %></td>
</tr>
<% end %>
and the error is gone but it does not display at the data and it's show blanks unless I put 'link_to' but they keep display like
and I have put on AdminController.rb
class AdminController < ApplicationController
before_action :authenticate_user!
def index
#user = User.all
#tools = Tool.all
end
end
seems I miss something, I have look google or stackover flow, most of them answer are very same as this code as I wrote
Update: as I am able to get some data like a phone number or email
Here is code i wrote
<% User.find_each do |user| %>
<tr>
<td><%= link_to user.id, user %></td>
<td><%= link_to user.email, user %></td>
<td><%= link_to user.created_at.strftime('%v'), user %></td>
<td><%= link_to user.fullname, user %></td>
<td><%= link_to user.phone_number, user %></td>
</tr>
<% end %>
but frustration with fullname as it should be displayed but it not

Set #user (or better #users) in the controller:
def index # or the actual action name
#users = User.all # or User.order(:fullname)
end

Related

Displaying has and belongs to many associations in index

Hey I'm new to Rails and all this so bear with me, thanks!
I have two models:
class User < ApplicationRecord
has_and_belongs_to_many :sports
end
class Sport < ApplicationRecord
has_and_belongs_to_many :users
end
My users have a few different sports that they can choose each. I'm simply trying to display all users in a table, along with which sports they do. However.. the only way I've managed to get anything without an error is by using current_user as shown below. I've been looking how to do this for hours... I know it's going to be stupidly simple but I just can't figure it out or even know how to go in the right direction.
# users_controller.rb
def index
#users = User.all
#sports = current_user.sports
end
# users/index.html.erb
<% #users.each do |user| %>
<tr>
<td><%= link_to user.name, user %></td>
<td><%= link_to user.email, user %></td>
<% #sports.each do |s| %>
<td><%= s.name %></td>
<% end %>
</tr>
<% end %>
That's my current code but obviously this shows only the signed in users associations and repeats it for the other users like this:
<table>
<tr>
<th>Name</th>
<th>Sport 1:</th>
<th>2:</th>
</tr>
<tr>
<td>User 1 (current_user)</td>
<td>Football</td>
<td>Running</td>
</tr>
<tr>
<td>User 2</td>
<td>Football (User 1's Sports)</td>
<td>Running </td>
</tr>
</table>
Thanks in advance.
You can try using the following and deleting #sports = current_user.sports:
<% user.sports.each do |s| %>
<td><%= s.name %></td>
<% end %>
using user.sports while looping through each of the user will lead to N+1 queries on your database. You can change your controller method to something like
def index
#users = User.all.eager_load(:sports)
end
and then in html
<% user.sports.each do |s| %>
<td><%= s.name %></td>
<% end %>
This will load users along with left_outer_join on sports table and this will save to lot of extra queries on your database.
For Info you can refer this good blog.
Thanks

How to display value of a field from a different table by using the value of a different column in another table

I realize the heading is a little confusing but my problem is quite simple. I hae two models in my rails 5 app. User and Expense. Each expense belongs_to a user. I have an index page where all expenses are being listed. I can list the user IDs for each expense from the expenses table but I want to instead look up the name of the user (in column username) in the users table and display it with the expense instead. The view I have written is below. But it doesn't work.
<p id="notice"><%= notice %></p>
<h1>Teamjournals</h1>
<table style="padding: 2px; width: 50%" border="2px" align="center">
<thead>
<tr>
<td align="center"><%= link_to new_expense_path, :class =>"btn btn-success btn-wide" do%>Add New Expense<% end %></td>
</tr>
<tr>
<th>User</th>
<th>Expense Date</th>
<th>Currency</th>
<th>Expense Amount</th>
<th>Description</th>
<th colspan="1"></th>
</tr>
</thead>
<tbody>
<% #expenses.each do |expense| %>
<tr>
<td><%= User.joins(:expense).where('expense.user_id = ?', #user.id) %></td>
<td><%= expense.expense_date %></td>
<td><%= expense.currency.currency %></td>
<td align="right"><%= expense.expense %></td>
<td><%= expense.description %></td>
</tr>
<% end %>
</tbody>
</table>
Ok so in your iteration over #expenses you have this line:
<%= User.joins(:expense).where('expense.user_id = ?', #user.id) %>
you can change it to this:
<% user = expense.user %>
Note that I'm using <% not <%= because I'm just trying to assign a variable, not print the output to html.
Then after defining user you can say <%= user.name %>.
You should read a bit more about active record associations, but here's a few side comments about the query you've shown
User.joins(:expense).where('expense.user_id = ?', #user.id)
In this case, you should use the method generated by belongs_to instead of writing a query. But in situations where you do want to write a custom query, you should only be using where when you want to get an array. In this case you're looking for a single record so you could use find_by. Furthermore, the joins you're doing here is unnecessary
# any of these works
user = User.where('id = ?', expense.user_id).first
user = User.where(id: expense.user_id).first
user = user.find_by(id: expense.user_id)

devise admin user approval setup

Seems like the tutorial located here has a couple omissions:
When creating the admin accessible controller method, they don't specify which custom devise controller to use, or which base controller to inherit from. So I've placed my code in a PagesController:
class PagesController < ApplicationController
def approve_users
if current_user.admin?
if params[:approved] == "false"
#users = User.find_by_approved(false)
else
#users = User.all
end
end
end
end
The view code that allows you to switch between all users and all unapproved users results in a NoMethodError in Pages#approve_users: undefined method 'each' for User whenever you select to show the users for whom :approved => false. I know why noMethodErrors spring up in app development, and would normally be able to wrap my head around why I'm getting this error. It works when #users = User.all, but not when #users = User.find_by_approved(false)
<% if current_user.admin? %>
<h2>Users</h2>
<%= link_to "All Users", :action => "approve_users" %> | <%= link_to "Users awaiting approval", :action => "approve_users", :approved => "false" %>
<div class="ui form">
<table>
<thead>
<tr scope="col">
<th>First name</th>
<th>Last name</th>
<th>E-mail</th>
<th>Approve</th>
</tr>
</thead>
<% #users.each do |user| %>
<tbody>
<tr>
<td><%= user.firstname %></td>
<td><%= user.lastname %></td>
<td><%= user.email %></td>
<td class="ui checkbox">
<input type="checkbox" tabindex="0" class="hidden">
</td>
</tr>
</tbody>
<% end %>
</table>
</div>
<% end %>
The wiki says it that it provides a simple way to approve users, but their view code actually just provides a simple way to list all users. I'm assuming that I need to use a form helper.
I made a custom admin controller specifically for an admin control panel and put all of the tools in an index page. You can probably do it a number of ways, though.
The common consensus on this seems to be that if you switch #users = User.find_by_approved(false) to #users = User.where(approved: false), it works better. That's what I currently have and it works very well.
I had this problem as well, and I ended up scrapping devise and making a custom user sign in method. You should be able to make it work, though. I followed the tutorial here and it helped immensely. Basically, you want to create a method which will approve users in your admin controller. This is the one I used:
`
def approve
User.where(id: params[:user_id]).update_all(approved: true)
redirect_to admin_index_path
end
From there, you add a put method to your routes.
put 'approve_admin', to: "admin#approve", as: :approve_admin
Finally, wrap your list of users in a form tag and add a hash of all of the user IDs you want to update as a hash.
<%= form_tag(approve_admin_path, method: :put) do %>
<% for user in #unapproved_users %>
<tr>
<td class="mdl-data-table__cell--non-numeric"><%= check_box_tag "user_id[]", user.id %></td>
<td><%= user.name %></td>
<td><%= user.email %></td>
</tr>
<% end %>
</tbody>
</table>
<%= submit_tag "Mark as approved", class: 'mdl-button mdl-js-button mdl-button--raised approve' %>
<% end %>
I made a method for approving users and another for unapproving users so I switched up the #users.each iteration in favor of a for iteration. I added #unapproved_users to my index method to make this work properly. Hope this works for you!

Ruby on Rails: Push Posts in to a hash and then show them

I'm creating a twitter-copy and right now I'm trying to get all the posts from all the users you follow and then show them on the home page. I've done this in PHP before, but I'm new at RoR so I might be trying to do this the wrong way.
a User has many Subscriptions
and a Subscription belongs to User
a User has many Posts
and a Post belongs to User
This is what i've got so far:
session_controller.rb
def get_posts
#sub = #current_user.subscriptions.first
Post.where("user_id = ?", #sub.following_id).find_each do |tweet|
render partial: 'shared/tweet', locals: {tweet: tweet}
end
end
I know .first gets only the first subscription, but I wanted to try to get just something out.
home.html.erb
<table>
<tr>
<th>Username</th>
<th>Tweet</th>
</tr>
<%= yield %>
</table>
_tweet.html.erb
<div class="tweet">
<td>Username here somehow</td>
<td><%= tweet.content %></td>
</div>
But right now nothing is coming up in the table.. So, what am I doing wrong? (am I doing anything right at all?)
Try this:
session_controller.rb
def get_posts
#sub = #current_user.subscriptions.first
#tweets = Post.where("user_id = ?", #sub.following_id)
end
home.html.erb
<table>
<thead>
<tr>
<th>Username</th>
<th>Tweet</th>
</tr>
</thead>
<tbody>
<% #tweets.each do |tweet| %>
<%= render 'shared/tweet', tweet: tweet %>
<% end %>
</tbody>
</table>
_tweet.html.erb
<tr class="tweet">
<td><%= tweet.user.name %></td> # Not sure
<td><%= tweet.content %></td>
</tr>
EDIT:
To get all the tweets for all the subscritions:
following_ids = #current_user.subscriptions.map(&:following_id)
#tweets = Post.where(user_id: following_ids)

Creating a top 5 Leaderboard with Ruby on Rails

Users on my site gain points everytime one of their followers clicks on a link they posted. Right now I am able to show a list of everyone by using,
#users = User.all
<table>
<tr>
<th>User</th>
<th>Points</th>
</tr>
<% #users.sort_by{|u| u.clicks.size }.reverse.each do |u| %>
<tr>
<td><%= u.name %></td>
<td><%= u.clicks.size %></td>
</tr>
<% end %>
</table>
How can I have the block go through all the users then only display the top 5? Using the break if method is not working.
How about:
#users.sort_by{|u| u.clicks.size }.reverse[0...5].each do |u|
Or do away with the reverse altogether by negating the sort_by:
#users.sort_by{|u| -u.clicks.size }[0...5].each do |u|
Or you can have the database do the sorting for you:
#users = Users.joins(:clicks).order("clicks.size DESC").limit(5)

Resources