View says Users is nil, but psql shows I have users - ruby-on-rails

I am trying to display all the users in a view. I am using Rails 4.1.0 on Ruby 2.1.1. I am also using Heroku.
When I run psql command 'select * from users' it shows 3 users. However, in the view it seems to think my #users variable is nil
This is what my view/controller/model look like:
view: (app/views/status/index.html.erb)
<% if current_user %>
<h1>All users</h1>
<% if #users.nil? %>
users is nil
<% else %>
<% #users.each do |user| %>
<%= user %>
<% end %>
<% end %>
4
<% else %>
<%= render 'welcome' %>
<% end %>
Controller: (app/controllers/users_controller.rb)
class UsersController < ApplicationController
def index
#users = User.all
end
end
Model: (app/models/user.rb)
class User < ActiveRecord::Base
class << self
def from_omniauth(auth)
provider = auth.provider
uid = auth.uid
info = auth.info.symbolize_keys!
user = User.find_or_initialize_by(uid: uid, provider: provider)
user.name = info.name
user.avatar_url = info.image
user.profile_url = info.urls.send(provider.capitalize.to_sym)
user.save!
user
end
end
has_many :comments, dependent: :delete_all
end
Any help or or thoughts on what I am doing wrong would be great.

For displaying list of User objects set in UsersController, the index view should be in the file named app/views/users/index.html.erb.
Not app/views/status/index.html.erb as you are using.
app/views/status/index.html.erb is not connected to the UsersController; so #users is nil there, and it is correctly showing the users is nil message.

Related

How can show the data related to logged in user in rails

I am trying display the task related to logged in user but on my html page nothing show except the tag data
task_controller.rb
class TaskController < ApplicationController
def all_task
if current_user.present?
#all_task = Task.find_by_user_id(#current_user.id)
render template: 'task/allTask'
end
end
end
routes.rb
get 'all_task' => 'task#all_task'
task.erb
<p>All Task</p>
<% if user_signed_in? %>
<%#all_task.daily_task %>
<%#all_task.date %>
<%#all_task.created_at %>
<%end %>
Start by setting up an assocation between users and tasks:
class User < ApplicationRecord
# ...
has_many :tasks
end
Then setup the route and controller:
get '/user/tasks', to: 'users/tasks#index', as: :user_tasks
# app/controllers/users/tasks_controller.rb
module Users
class TasksController < ApplicationRecord
before_action :authenticate_user!
# display all the tasks belonging to the currently signed in user
# GET /user/tasks
def index
#tasks = current_user.tasks
end
private
# You don't need this if your using Devise
def authenticate_user!
unless current_user
redirect_to '/path/to/your/login',
notice: 'Please sign in before continuing'
end
end
end
end
Note that when you have a route like this that displays resources that belong to the current user you should use a callback to bail early and redirect the user to sign in instead of using if current_user.present? and giving a response which is meaningless to the user. This code should be DRY:ed into your ApplicationController (even better yet is to not reinvent the auth wheel).
You can link to the users tasks with:
<% if current_user.present? %>
<%= link_to 'My tasks', user_tasks_path %>
<% end %>
In your view you need to iterate across the returned tasks:
# app/views/users/tasks/index.html.erb
<p>All Tasks</p>
<% if #tasks.any? %>
<% #tasks.each do |task| %>
<%= task.daily_task %>
<%= task.date %>
<%= task.created_at %>
<% end %>
<% else %>
<p>You don't have any tasks.</p>
<% end %>
You can cut duplication here by using partials.
Can you make sure if the instance variable #current_user is defined? If not, try the following:
class TaskController < ApplicationController
def all_task
if current_user.present?
#all_task = Task.find_by_user_id(current_user.id)
render template: 'task/allTask'
end
end
end
instead of
class TaskController < ApplicationController
def all_task
if current_user.present?
#all_task = Task.find_by_user_id(#current_user.id)
render template: 'task/allTask'
end
end
end

Rails 5: Combining two ActiveRecord Models

I'm currently trying to display the users that where invited by the current user and I also want to display the last reservation the made, if they made one.
My Users Controller:
#users = User.where(invited_by_id: current_user.id)
My View:
<% #users.each do |user| %>
<%= user.fullname %> #Works
<%= user.invited_by.fullname %> #Works
<% end %>
What I've already tried:
<% #users.each do |user| %>
<% user.reservations.each do |reservation| %>
<%= reservation.user.fullname %> #Works
<%= reservation.price %> # Works
<% end %>
<% end %>
But this gives me all reservations a user made, I only want the first reservation from the user and therefore only one table for each user.
Is it possible to achieve this in the view or do I need to make some changes in my controller ?
since you only need first reservation from each user, the custom associations (has_one) below can help your query in controller
User.rb
class User < ActiveRecord::Base
has_many :reservations
has_one :first_reservation, -> { order('created_at ASC')}, class_name: "Reservation"
end
User Controller:
#users = User.where(invited_by_id: current_user.id).preload(:first_reservation)
# preload will make sure load the reservation record as well to prevent n+1
your view combined user and first reservation, since you already setup has_one, you can call user.first_reservation
<% #users.each do |user| %>
<%= user.fullname %>
<%= user.first_reservation.price %>
<% end %>

How to write a custom function in a model in ruby on rails?

I have a User model class I have created with Devise.
I have a role field (admin=0, user=1) in my model.
Screenshot of my database:
HTML View
<% if current_user.active_admin? %>
<%= render 'layouts/admin' %>
<% else %>
<%= render 'layouts/user' %>
<% end %>
Model
def active_admin?
#your logic here
end
I want to login. If I am an admin check role is 0 render to layouts/admin else I am a user check role is 1 render to layouts/user.
How do I write code in the model to do this?
In your user.rb file:
class User < ActiveRecord::Base
def active_admin?
role == 0
end
end
In your view:
<% if current_user.active_admin? %>
<%= render 'layouts/admin' %>
<% else %>
<%= render 'layouts/user' %>
<% end %>
As Mark says, you can just check role for 0 or 1.
Any column in your database will map directly to a method on the model.
A couple of points:
If you're using Rails 5 you'll need to inherit from ApplicationRecord rather than ActiveRecord::Base.
In newer versions of Ruby you can use the #zero? method:
class User < ApplicationRecord
def active_admin?
role.zero?
end
end
No need of adding a method for checking the roles, you can directly achieve this by below change. It will return true for anything other than 0.
<% if current_user.role? %>
<%= render 'layouts/user' %>
<% else %>
<%= render 'layouts/admin' %>
<% end %>
One way can be add an method on application controller as
def after_sign_in_path_for(resource_or_scope)
if current_user.role==0
#your admin path
else
root_path
end
end
def authenticate_admin
unless (user_signed_in? and current_user.role !=0 )
redirect_to '/users/sign_in'
end
end
add to the required controller
before_filter :authenticate_admin
layout 'admin'

act_as_followers get all posts of user I'm following

Im trying to get all the Posts from the the Users. I'm following using the act_as_follower gem. The User follows a profile model, and Posts belong to a User.
My User model:
acts_as_follower
My Profile model the user follows:
belongs_to :user
acts_as_followable
Post model:
belongs_to :user
My Post Controller.rb:
def follow
#profile = Profile.find(params[:id])
current_user.follow(#profile)
redirect_to :back
end
def unfollow
#profile = Profile.find(params[:id])
current_user.stop_following(#profile)
redirect_to :back
end
Im trying to implement something like this using follows_by_type method provided:
#posts = current_user.follows_by_type('Post').order("created_at DESC")
But the thing is the User follows the Profile model, but here I'm looking for a type 'Post'.
EDIT
In my index controller i'v set up the following:
#favoritePost = Post.where(user_id: current_user.all_follows.pluck(:id))
And in the view iv implemented this:
<% if user_signed_in? %>
<%#favoritePost.each do |post| %>
<%= post.title %>
<% end %>
<% end %>
The gem lets you follow multiple models and follows_by_type('Post') filters the Posts you follow.
What you're looking to do is to return the posts from the users you follow.
Controller
#posts = Post.where(user_id: current_user.all_following.pluck(:id))
View
<% #posts.each do |post| %>
<%= post.title %>
<% end %>
I worked out this solution, might not be the best, but it works as required.
In my controller i set this up:
#following = current_user.all_following
#followposts = #following.each do |f|
f.user.id
end
And in my view I have set this up:
<% #followposts.each do |f| %>
<% f.user.posts.each do |g| %>
<%= g.title %>
<% end %>
<% end %>

Nested sign up form does not display the error messages for the nested object

Organization and User have a many-to-many relationship through Relationship. There's a joined signup form. The sign up form works in that valid information is saved while if there's invalid information it rolls back everything.
The problem is that the form does not display the error messages for the nested User object. Errors for Organization are displayed, the form correctly re-renders if there are errors for User, but the errors for User are not displayed.
Why are the errors when submitting invalid information for users not displayed? Any help is appreciated.
The signup form/view:
<%= form_for #organization, url: next_url do |f| %>
<%= render partial: 'shared/error_messages', locals: { object: f.object, nested_models: f.object.users } %>
... fields for organization...
<%= f.fields_for :users do |p| %>
...fields for users...
<% end %>
<%= f.submit "Register" %>
<% end %>
The shared error messages partial:
<% if object.errors.any? %>
<div id="error_explanation">
<div class="alert alert-danger">
The form contains <%= pluralize(object.errors.count, "error") %>.
</div>
<ul>
<% object.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<% if defined?(nested_models) && nested_models.any? %>
<div id="error_explanation">
<ul>
<% nested_models.each do |nested_model| %>
<% if nested_model.errors.any? %>
<ul>
<% nested_model.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
<% end %>
<% end %>
</ul>
</div>
<% end %>
The controller method:
def new
#organization = Organization.new
#user = #organization.users.build
end
def create
#organization = Organization.new(new_params.except(:users_attributes))
#organization.transaction do
if #organization.valid?
#organization.save
begin
#user = #organization.users.create!(users_attributes)
#relationship = #organization.relationships.where(user: #user).first
#relationship.update_attributes!(member: true, moderator: true)
rescue
raise ActiveRecord::Rollback
end
end
end
if #organization.persisted?
if #organization.relationships.where('member = ? ', true).any?
#organization.users.where('member = ? ', true).each do |single_user|
single_user.send_activation_email
end
end
flash[:success] = "A confirmation email is sent."
redirect_to root_url
else
#user = #organization.users.build(users_attributes) if #organization.users.blank?
render :new
end
end
The Organization model:
has_many :relationships, dependent: :destroy
has_many :users, through: :relationships, inverse_of: :organizations
accepts_nested_attributes_for :users, :reject_if => :all_blank, :allow_destroy => true
validates_associated :users
The Relationship model:
belongs_to :organization
belongs_to :user
The User model:
has_many :relationships, dependent: :destroy
has_many :organizations, through: :relationships, inverse_of: :users
Update: If I add an additional line to def create as below, it seems to work, i.e., then it does display the error messages. However, then it for some reason doesn't save when valid information is submitted. Any ideas how to deal with that?
def create
#organization = Organization.new(new_params.except(:users_attributes))
#user = #organization.users.new(users_attributes)
#organization.transaction do
...
Maybe try this:
<%= render partial: 'shared/error_messages',
locals: { object: f.object, nested_models: [ #user ] } %>
I guess the call to #organization.users.blank? doesn't work in the way you expected it to do, as the user is not correctly created, because #create! threw an exeption. Rails probably does a check on the database, to see if there are any users now, and thinks there is still nothing in there. So your #organization.users.build(users_attributes) gets called, but this doesn't trigger validation.
In general I would also recommend you the use of a form object (like in the other answer), when creating complex forms, as this clarifies things like that and makes the view more clean.
This is classic use case for form objects. It is convenient from many perpectives (testing, maintainance ...).
For example:
class Forms::Registration
extend ActiveModel::Naming
include ActiveModel::Conversion
include ActiveModel::Validations
def persisted?
false
end
def initialize(attributes = {})
%w(name other_attributes).each do |attribute|
send("#{attribute}=", attributes[attribute])
end
end
validates :name, presence: true
validate do
[user, organization].each do |object|
unless object.valid?
object.errors.each do |key, values|
errors[key] = values
end
end
end
end
def user
#user ||= User.new
end
def organization
#organization ||= Organization.new
end
def save
return false unless valid?
if create_objects
# after saving business logic
else
false
end
end
private
def create_objects
ActiveRecord::Base.transaction do
user.save!
organization.save!
end
rescue
false
end
end
the controller:
class RegistrationsController < ApplicationController
def new
#registration = Forms::Registration.new
end
def create
#registration = Forms::Registration.new params[:registration]
if #registration.save
redirect_to root_path
else
render action: :new
end
end
end
and the view in HAML:
= form_for #registration, url: registrations_path, as: :registration do |f|
= f.error_messages
= f.label :name
= f.text_field :name
= f.submit
It is worth to read more about form objects.
Nested attributes bit me SOOO hard every time I decided it's a good time to use them, and I see you know a bit of what I'm talking about.
Here's a suggestion of a different approach, use a form object instead of nested attributes: http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/ see under section 3. Extract Form Objects
You can extract your existing validations on the User model into a module and import that, to expand on the solution from the blog:
https://gist.github.com/bbozo/50f8638787d6eb63aff4
With this approach you can make your controller code super-simple and make simple and fast unit tests of the not-so-simple logic that you implemented inside and save yourself from writing integration tests to test out all different possible scenarios.
Also, you might find out that a bunch of the validations in the user model are actually only within the concern of the signup form and that those validations will come and bite in later complex forms, especially if you're importing data from a legacy application where validations weren't so strict, or when you one day add additional validators and make half of your user records invalid for update.
I had a similar problem. everything seemed to work fine, but I was not getting any errors The solution i found is to build the comment in article#show instead of the view:
#article = Article.find(params[:id])
#comment = #article.comments.build(params[:comment])
and in your articles#show don't use #article.comments.build but #comment:
<%= form_for([#article, #comment]) do |f| %>
<%= render 'shared/error_messages', :object => f.object %>
<p><%= f.submit %></p>
<% end %>
make sure you build the comment in your comment#create as well (you really have no choice though :P)
I think you need to pass f.object instead of #comment.
In case someone might be looking for a solution to render form errors in a form, try:
f.object.errors["account.address"].present?`
The address is the nested attribute here.

Resources