Passing a variable to a partial - ruby-on-rails

I know this has been asked before but I think I'm doing everything right and it still wont work.
I have a simple user table one to many with a relationship table. I just want to show the number of people following a selected user in a partial.
It works fine in the non partial view but I keep getting the error:
undefined method `name'
when I make the normal view into a partial and it highlights the focus of the error as being
def gravatar_for(user, size = 30, title = user.name)
which is fromm a helper method I use
the partial is here (called users/_show_follow ):
<% provide(:title, #title) %>
<div class="row">
<aside class="col-md-4">
<section class="user_info">
<%= gravatar_for user %>
<h1><%= user.name %></h1>
<span><%= link_to "view my profile", user %></span>
</section>
<section class="stats">
<%= render 'shared/stats' %>
<% if users.any? %>
<div class="user_avatars">
<% for user in users %>
<%= link_to gravatar_for(user, size: 30), user %>
<% end %>
</div>
<% end %>
</section>
</aside>
<div class="col-md-8">
<h3><%= #title %></h3>
<% if users.any? %>
<ul class="users follow">
<%= render users %>
</ul>
<%= will_paginate %>
<% end %>
</div>
</div>
The originating page for the partial:
<div class="container-fluid">
<div class="row-fluid">
<div class="col-md-8">
<div id="chart"><%= javascript_include_tag('graph') %></div>
</div>
<div class="col-md-2">
<p>
<h2>Node Score</h2>
<div id="FBDiv"></div>
<div id="chart_1"></div>
<h2>Node Profile</h2>
<div id="NodeProfile"></div>
<h2>My inner circle</h2>
<h2>Wants to connect</h2>
<h2>My profile</h2>
<%= current_user.about %>
<section class="stats">
<%= render 'shared/stats' %>
<%= render :partial => "show_follow", :locals => {:user => #user, :users => #users} %>
</section>
</section>
</div>
</div>
</div>
<div class="container-fluid">
<div class="row">
<div class="col-md-4"></div>
</div>
</div>
the controller
class UsersController < ApplicationController
def index
#users = User.including_relationships
respond_to do |format|
format.html # index.html.erb
format.json { render json: #users }
end
end
def show
#user = User.find_by name: params[:name]
respond_to do |format|
# Here we need to remove the layout because the request
# is done via ajax and the layout is already loaded.
format.json { render json: #user.to_json }
end
end
def following
#title = "Following"
#user = User.find(params[:id])
#users = #user.followed_users.paginate(page: params[:page])
render 'show_follow'
end
def followers
#title = "Followers"
#user = User.find(params[:id])
#users = #user.followers.paginate(page: params[:page])
render 'show_follow'
end
end
the helper
module ApplicationHelper
def page_header(text)
content_for(:page_header) { text.to_s }
end
def gravatar_for(user, title = user.name, size = 30)
image_tag gravatar_image_url(user.email, size: size), title: title, class: 'img-rounded'
end
end
Is the problem how I pass the variable into the helper method from the partial?

As you pointed out the error is on your helper arguments: def gravatar_for(user, size = 30, title = user.name). user is not an object, it'simply the name of the argument, so user.name won't work.
Try setting a default title (1) or passing the title when you call the method (2):
def gravatar_for(user, size = 30, title = 'Default name')
<%= gravatar_for user, 20, user.name %>. To avoid passing the size each time you can reorder the arguments: def gravatar_for(user, title = user.name, size = 30) or use keyword arguments.

Related

Rails erb adding extra template without id

Link to image of what I'm talking about
My problem is that there is an extra template being rendered at the bottom of my list without an item id. The icons delete the item they are next to when clicked. The bottom icon is showing up even though it has no item related to it.
Here is my the show html.erb
<div class="row">
<div class="col-md-8">
<div class="media">
<br />
<div class="media-body">
<h3><%= #user.email %></h3>
<br />
<%= render partial: 'items/form', locals: {user: #user} %>
<div class="media">
<div class="media-body">
<h4 class="media-heading">
<ul>
<%= render #items %>
</ul>
</h4>
</div>
</div>
</div>
</div>
</div>
Here is my _item template
<li><%= item.name %><%= link_to "", [current_user, item], remote: true, method: :delete, class: 'glyphicon glyphicon-ok' %></li>
Here is my items controller
class ItemsController < ApplicationController
def create
#item = Item.new(item_params)
#item.user = current_user
if #item.save
flash[:notice] = "Item was saved."
redirect_to user_path(current_user.id)
else
flash.now[:alert] = "There was an error saving the item. Try again."
redirect_to user_path(current_user.id)
end
end
def destroy
#item = Item.find(params[:id])
if #item.destroy
flash[:notice] = "Item deleted"
redirect_to user_path(current_user.id)
else
flash.now[:alert] = "Error deleting the item."
redirect_to user_path(current_user.id)
end
end
private
def item_params
params.require(:item).permit(:name)
end
end
Here is my users controller
class UsersController < ApplicationController
def show
#user = current_user
#item = Item.new
#items = #user.items
end
end
The items belong to the users and have nested routes under user. The last checkmark (the one I want to get rid of) when hovered over shows the link .../users/6/items, while the others that next to items show .../users/6/items/40
Here is my _form.html.erb for items:
<%= form_for [user, user.items.new] do |f| %>
<%= f.text_field :name, class: 'form-control', placeholder: "Enter your to-do item", value: nil, required: true %>
<div class="form-group">
<%= f.submit "Save", class: 'btn btn-success' %>
</div>
<% end %>
Remove
#item = Item.new
from show action in users controller.
class UsersController < ApplicationController
def show
#user = current_user
#items = #user.items
end
end

Rails: Get params from click

I'm working on a Pinterest-like app to learn Rails, where users can collect items and add them to collections.
I have an "Add to collection" button which opens a modal with a list of all collections of a user. This works fine on individual item show pages, but not on my item index page (which lists all items that have been posted).
This is my collections controller:
def index
#item = Item.find(params[:item_id])
#selected_collections = selected_collections(#item.id)
#collections = current_user.collections
respond_to do |format|
format.js {
render
}
end
end
My items controller:
def index
#items = Item.all.order(created_at: :desc).paginate(:page => params[:page], :per_page => 20)
#collections = current_user.collections
#selected_collections = selected_collections(item.id)
end
def show
#item = Item.find_by_id(params[:id])
return render_not_found if #item.blank?
#collections = current_user.collections
#selected_collections = selected_collections(#item.id)
end
This is my Add-to-collection button, which should be shown for each item on the index:
<%= link_to "+ Add", item_collections_path(item, format: :js), class: 'btn btn-secondary btn-30', data: {toggle: 'modal', target: '#CollectionModal'}, remote: true, format: :js %>
And part of the corresponding modal:
<div class="modal-body">
<%= render 'collections/collections_list', :collections=>#collections, :selected_collections=>#selected_collections %>
</div>
_collection_list.html.erb
<div id="collection_list">
<% #collections.each do |collection| %>
<%= render 'collections/collection_checkbox', collection: collection, selected_collections: selected_collections %>
<% end %>
<%= render 'collections/collection_checkbox', collection: Collection.new, selected_collections: selected_collections %>
<div style='display: none;' class="new_collection_template">
<%= render 'collections/collection_checkbox', collection: Collection.new, selected_collections: selected_collections %>
</div>
_collection_checkbox.html.erb
<div class="form-check">
" <%= 'checked' if selected_collections.include?(collection.id) %> <%= "disabled" unless collection.id %>>
<%= collection.collection_name %>
<% if !collection.id %>
<input type="text" class="collection-name" placeholder="New collection" />
<% end %>
On my index I get the following error message:
undefined local variable or method `item' for
ItemsController:0x007f69022aefa0 Did you mean? item_url items_url item_path #items
Screenshot of Error Message
I assume that this is because I don't have individual #item defined on my index. On the item show pages I can simply find the params in the URL. But how can I solve this problem on the index?
Thanks for your help, much appreciated :)

undefined method `any?' for nil:NilClass 2

i'm trying to show all the videos in my app so when i'm adding a new video and want to redirect to movie_path so i did this in my video controller:
def create
#video = Video.new(video_params)
if #video.save
flash[:success] = 'Video added!'
redirect_to movie_path(#movies)
else
render :new
end
end
it gives me an error:
undefined method `any?' for nil:NilClass
this is my show page that want to show the video:
<% if #videos.any? %>
<div class="container">
<div id="player-wrapper"></div>
<% #videos.in_groups_of(3) do |group| %>
<div class="row">
<% group.each do |video| %>
<% if video %>
<div class="col-md-4">
<div class="yt_video thumbnail">
<%= link_to image_tag("https://img.youtube.com/vi/#{video.uid}/mqdefault.jpg", alt: video.title,
class: 'img-rounded'),
"https://www.youtube.com/watch?v=#{video.uid}", target: '_blank' %>
<div class="caption">
<h5><%= video.title %></h5>
<p>Published at <%= video.published_at.strftime('%-d %B %Y %H:%M:%S') %></p>
<p>
<span class="glyphicon glyphicon glyphicon-thumbs-up"></span> <%= video.likes %>
<span class="glyphicon glyphicon glyphicon-thumbs-down"></span> <%= video.dislikes %>
</p>
</div>
</div>
</div>
<% end %>
<% end %>
</div>
<% end %>
this is movie controller:
def index
#movies = Movie.all.order(:cached_votes_score => :desc)
#movies = #movies.paginate(:page => 1, :per_page => 8)
end
def show
#reviews = Review.where(movie_id: #movie.id).order("created_at DESC")
end
def new
#movie = current_user.movies.build
#movie = Movie.new
#categories = Category.all.map{|c| [ c.name, c.id ] }
end
and this is the routes i have:
nil don't have method any? so you must protect your code against it
instead this line:
<% if #video.any? %>
write this:
<% if #video.try(:any?) %>
I think you have not defined #videos, you have defined #video, so you should try this:
<% if #video.any? %>

How do I create a checklist and destroy its items using ajax?

I am working on a rails assignment that needs me to create a checkbox that destroys items on a to-do list. I am currently getting a undefined local variable or method `item,' but I don't think thats the overall problem with my items#destroy action. Should I be making item to be #item instead?
Items Controller:
class ItemsController < ApplicationController
def new
#user = User.find(params[:user_id])
#item = Item.new
end
def create
#user = User.find(params[:user_id])
#item = Item.new(params.require(:item).permit(:name))
#item.user_id = #user.id
if #item.save
flash[:notice] = "Item was saved."
redirect_to [#user, #item]
else
flash[:error] = "There was an error saving the item. Please try again."
render :new
end
end
def show
#user = User.find(params[:user_id])
#item = Item.find(params[:id])
end
def destroy
#user = User.find(params[:user_id])
#item = Item.find(params[:id])
if #item.destroy
flash[:notice] = "Item was removed."
else
flash[:error] = "Item couldn't be deleted. Try again."
end
respond_to do |format|
format.html
format.js
end
end
Destroy.js.erb
$('#item-' +<%= #item.id %>).hide();
Users Show:
<br>
<div class="container">
<div class="row">
<div class="col-md-11">
<div class="panel panel-default">
<div class="panel-body">
<div class="row">
<div class="col-md-12 lead">User profile<hr></div>
</div>
<div class="row">
<div class="col-md-4 text-center">
<img class="img-circle avatar avatar-original" style="-webkit-user-select:none;
display:block; margin:auto;" src="http://robohash.org/sitsequiquia.png?size=120x120">
</div>
<div class="col-md-8">
<div class="row">
<div class="col-md-12">
<h1 class="only-bottom-margin"><%= #user.email%></h1>
</div>
</div>
<div class="row">
<div class="col-md-6">
<span class="text-muted">Name:</span> <%= #user.name%><br>
<span class="text-muted">Id:</span> <%= #user.id %><br>
</div>
<div class="col-md-10">
<h3>User's To-Do List</h3>
<%= link_to "", item, method: :delete, class: 'glyphicon glyphicon-ok', remote: true %>
<%= render partial: 'items/item'%>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
By the time your view is called (i.e. destroy.js.erb), #item will be destroyed. Just add a variable that caches the item id:
def destroy
#user = User.find(params[:user_id])
#item = Item.find(params[:id])
#item_id = #item.id
if #item.destroy
flash[:notice] = "Item was removed."
else
flash[:error] = "Item couldn't be deleted. Try again."
end
respond_to do |format|
format.html
format.js
end
and then in your destroy.js.erb:
$('#item-' +<%= #item_id %>).hide();
I believe the error is being introduced in your view with the line:
<%= link_to "", item, method: :delete, class: 'glyphicon glyphicon-ok', remote: true %>
I don't see a setter for 'item' anywhere, which would prevent the link_to method from inferring its type and route.
What appears to be missing is a loop through the user's items, something along the lines of...
<h3>User's To-Do List</h3>
<% #user.items.each do |item| %>
<%= link_to "", item, method: :delete, class: 'glyphicon glyphicon-ok', remote: true %>
<%= render partial: 'items/item'%>
<% end %>
Note that this solution makes an assumption about the relationship between User and Item, specifically a has_many :items in the User.rb model.

ajax like/unlike post in rails 4

Ive been working to implement a like/unlike feature which works with ajax. I have already built and tested the models and associations which seem to working fine. What I am having problems with is rendering the actual like/unlike button in the view. I have been using this https://github.com/Aufree/ting/tree/master/app/controllers github projects like/unlike system as reference for building my own.
Heres my controller likeships_controller.rb
before_action :authenticate_user!
include LikeshipsHelper
def create
current_user.like!(params[:likeable_type], params[:likeable_id])
respond_to do |format|
format.html { redirect_to correct_path }
format.js
end
end
def destroy
current_user.unlike!(params[:likeable_type], params[:likeable_id])
respond_to do |format|
format.html { redirect_to correct_path }
format.js
end
end
Heres my likeship_helper.rb
module LikeshipsHelper
def likeable_likes_tag like
#count = Likeship.where("likeable_type = ? and likeable_id = ?", like[:likeable_type], like[:likeable_id]).count
if #count > 0
likes_count = #count
else
likes_count = ''
end
if current_user && current_user.liking?(like)
link_title = "unlike"
link_path_method = "delete"
fa_icon = '<i class="red heart icon"></i>'
else
link_title = "like"
link_path_method = "post"
fa_icon = '<i class="red heart empty icon"></i>'
end
if current_user.blank?
"#{likes_count}#{fa_icon}".html_safe
else
link_to "#{likes_count}#{fa_icon}".html_safe,
likeships_path(like),
title: link_title,
class: "animated zoomIn",
method: link_path_method,
remote: true
end
end
def correct_path
if params[:likeable_type].to_s == "Post"
post_path(params[:likeable_id])
end
end
end
these are my views
_like.html.erb
<i class="red heart icon">
<%= form_for(current_user.likeships.build) do |f| %>
<%= f.hidden_field :likeable_type, value: #likeable[:likeable_type] %>
<%= f.hidden_field :likeable_id, value: #likeable[:likeable_id] %>
<%= f.submit %>
<% end %>
</i>
_likes.html.erb
<% if user_signed_in? %>
<% if current_user.liking?(#likeable) %>
<%= render 'likeships/unlike' %>
<% else %>
<%= render 'likeships/like' %>
<% end %>
<% end %>
EDIT: Now if i use this in the _post.html.erb view no error is thrown but no like/unlike button appears either.
<div class="post_wrapper">
<div class="media_wrapper">
<span class="name"><%= link_to post.user.name, post.user, class: "name" %></span>
<p class="media"><%= post.body_html %></p>
<div class="date_and_like">
<span class="item" id="like-post-#{#post.id}" >
<% #likeable = Likeship.likeable(#post) %>
<%= likeable_likes_tag #likeable %>
</span>
<span class="timestamp"><%= time_ago_in_words(post.created_at) %> ago </span>
</div>
</div>
heres the create.js.erb file
$("#like-post-<%= params[:likeable_id] %>").html("<%= j(likeable_likes_tag #likeable) %>")
So I also tried to render the likes form in the post view with this
but it gave me an error that
undefined method `[]' for nil:NilClass
Ive been stumped for hours trying to figure this out any help would be awesome, also let me know if you need any additional info, Thanks.

Resources