undefined method `any?' for nil:NilClass 2 - ruby-on-rails

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? %>

Related

Ruby on Rails form error not giving any output/ not working

Hello guys I searched everywhere on how to output form errors but no luck. I tried almost all the code I found on the internet but still didn't work.
Here are some of my files:
view/books/new.html.erb
<div class="container">
<h2>Create a new book</h2>
<%= form_with model: #book, url: create_new_book_path do |f| %>
<% if #book.errors.any? %>
<ul>
<% #book.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
<% end %>
<div class="form-group row">
<%= label_tag(:title, "Title:", class: "col-sm-2 col-form-label") %>
<div class="col-sm-10">
<%= f.text_field :title, class: "form-control" %>
</div>
</div>
<div class="form-group row">
<%= label_tag(:price, "Price:", class: "col-sm-2 col-form-label") %>
<div class="col-sm-10">
<%= f.text_field :price, class: "form-control" %>
</div>
</div>
<div class="form-group row">
<%= label_tag(:subject_id, "Subject:", class: "col-sm-2 col-form-label") %>
<div class="col-sm-10">
<%= f.collection_select :subject_id, #subjects, :id, :name, class: "form-control" %>
</div>
</div>
<div class="form-group row">
<%= label_tag(:description, "Book description:", class: "col-sm-2 col-form-label") %>
<div class="col-sm-10">
<%= f.text_area :description, class: "form-control" %>
</div>
</div>
<%= submit_tag "Create book", class: "btn btn-success" %>
<%= link_to "Cancel", books_path, class: "btn btn-danger" %>
<% end %>
<br/>
</div>
books_controller.rb
class BooksController < ApplicationController
def index
#books = Book.all
end
def show
#book = Book.find(params[:id])
end
def new
#book = Book.new
#subjects = Subject.all
end
def create
#book = Book.new(book_params)
end
def book_params
params.require(:book).permit(:title, :price, :subject_id, :description)
end
def edit
#book = Book.find(params[:id])
#subjects = Subject.all
end
def update
#book = Book.find(params[:id])
if #book.update_attributes(book_params)
redirect_to action: "index"
else
#subjects = Subject.all
render action: "edit"
end
end
def destroy
Book.find(params[:id]).destroy
redirect_to action: "index"
end
end
routes.rb
get 'books/new', to: 'books#new', as: 'new_book'
post 'books/create', to: 'books#create', as: 'create_new_book'
view/layouts/application.html.erb
<main role="main">
<%= yield %>
</main>
I don't really know what I'm missing to get the errors, grateful for your answers!!
try putting them in a flash like this and render it in your view
def create
#book = Book.new
if #book.update(book_params)
flash[:notice] = 'success'
redirect_to action: 'index'
else
flash[:alert] = #book.errors.full_messages.join(', ')
redirect_to action: 'index'
end
end
and in your view render those flashes like
<% if flash[:notice]%>
<span class='notice'><%= flash[:notice] %></span>
<% end %>
<% if flash[:alert]%>
<span class='alert'><%= flash[:alert] %></span>
<% end %>

Having problems setting a delete route

Took me a while but finally was able to have a user_id and friend_id associate with each other through friendships model. The problem I'm having is:
When clicking "add friend"
<% #users.each do |user| %>
<% if user.user_name != current_user.user_name %>
<% if #friendshiplink.nil? %>
<%= user.user_name %>
<%= link_to "Add Friend", friendships_path(friend_id: user.id), method: :post %>
<% else %>
<%= link_to(
("Unfollow"),
"/friendships/#{ #friendship.id }",
method: :delete ) %>
<% end %>
<% end %>
<% end %>
I get in respond is:
undefined method `id' for nil:NilClass
Extracted source (around line #86):
<% else %>
<%= link_to(
("Unfollow"),
"/friendships/#{ #friendship.id }",
method: :delete ) %>
<% end %>
<% end %>
Please let me know if I'm missing any code in order to further understand what might be the issue
Rake Routes
friendships POST /friendships(.:format) friendships#create
friendship DELETE /friendships/:id(.:format) friendships#destroy
Friendship Controller
class FriendshipsController < ApplicationController
def create
# #friendship = current_user.friendships.build
# #friendship.friend_id = params[:friend_id]
# #friendship.user_id = current_user.id
#friendship = current_user.friendships.build(friend_id: params[:friend_id])
if #friendship.save
flash[:notice] = "Added friend."
redirect_to "/users/#{ params[:friend_id] }"
else
flash[:notice] = "Unable to add friend"
redirect_to root_url
end
end
def destroy
#friendship = current_user.friendships.find(params[:id])
#friendship.destroy
flash[:notice] = "Removed friendship."
redirect_to current_user
end
private
def friendship_params
params.require(:friendship).permit(:user_id, :friend_id)
end
end
User Controller
def index
#user = User.new
#users = User.all
if current_user
#leaders = #current_user.leaders
end
end
def create
#user = User.new(user_params)
if #user.save
session[:user_id] = #user.id
cookies[:user_id] = #user.id
flash[:notice] = "Successfully Registerd"
redirect_to "/"
else
flash[:alert] = #user.errors.full_messages
redirect_to "/"
end
end
def new
#user = User.new
end
def edit
#user = User.friendly.find(params[:id])
current_user
end
def show
#users = User.all
#user = User.friendly.find(params[:id])
current_user
if #current_user
#followerlink = Follower.where(leader_id: #user.id,
follower_id: #current_user.id).first
#friendshiplink = Friendship.where(friend_id: #user.id,
user_id: #current_user.id).first
end
end
def update
#user = User.friendly.find(params[:id])
if #user.update(user_params)
flash[:notice] = "You have successfully update your information"
redirect_to "/"
else
flash[:alert] = #user.errors.full_messages
redirect_to "/"
end
end
def destroy
#user = User.friendly.find(params[:id])
#user.destroy
end
private
def user_params
params.require(:user).permit(:background, :username_or_email, :first_name, :last_name, :email, :password, :user_name, :avatar, :gender, :zip_code, :birthdate)
end
Where code is in user/view
<div id="user_profile">
<div id="profile_top">
<p class="profile_logo"></p>
<nav>
<div class="profile_loginout">
<%= link_to ("LOGOUT"), "/sessions/new",method: :delete %>
</div>
<div class="profile_user-links">
<a href="/users/<%= current_user.id %>">
<% if current_user.user_name.present? %>
<%= link_to current_user.user_name, user_path(current_user) %>
<% else %>
<%= current_user.first_name %>
<% end %>
</a>
<b class="size">|</b>
Settings
<b class="size">|</b>
</div>
</nav>
</div>
<div id="profile_to">
<div class="profile_background_picture">
<%= image_tag #user.background.url(:medium) %>
</div>
<div class="profile_picture">
<%= image_tag #user.avatar.url(:medium) %>
</div>
</div>
</div>
<% if #current_user && #user.id != #current_user.id %>
<% if !#followerlink %>
<form action="/followers" method="POST">
<input type="hidden"
name="authenticity_token"
value="<%= form_authenticity_token %>">
<input type="hidden"
name="leader_id"
value=<%= #user.id %>>
<input type="submit" value="Follow" class="followlink">
</form>
<% else %>
<div class="followlink">
<%= link_to(
("Unfollow"),
"/followers/#{ #followerlink.id }",
method: :delete ) %>
</div>
<% end %>
<% end %>
<p>Username: <%= #user.user_name %></p>
<h2>Friends</h2>
<ul>
<% for friendship in #user.friendships %>
<li>
(<%= link_to "remove", friendship, method: :delete %>)
</li>
<% end %>
</ul>
<p><%= link_to "Find Friends", users_path %></p>
<h2> Users who Have Befriended you </h2>
<ul>
<% for user in #user.inverse_friends %>
<li> <%= h user.user_name %></li>
<% end %>
</ul>
<% #users.each do |user| %>
<% if user.user_name != current_user.user_name %>
<% if #friendshiplink.nil? %>
<%= user.user_name %>
<%= link_to "Add Friend", friendships_path(friend_id: user.id), method: :post %>
<% else %>
<%= link_to "Unfollow", friendships_unfollow_path(#friendship), method: :delete %>
<% end %>
<% end %>
<% end %>
Thank you for all the help or hints in solving the issue. Greatly appreciate it.
On top of my head, not sure it's working but try it...
In routes:
delete '/friendships/:id', to: 'friendships_controller#destroy', as: 'friendships_unfollow'
In view:
<%= link_to "Unfollow", friendships_unfollow_path(#friendship), method: :delete %>
It is unclear where do you get your #friendship variable.

Undefined method 'each' for nil class in create method

I'm getting an undefined method 'each' for nil class in my create method for a join table that I have.
I've got one join table for Emotions_pins and one for casues_pins the emotions pins table works fine but I'm getting the error on causes. Here's the code
_form.html.erb for Pin
<%= form_for(#pin) do |f| %>
<%= f.hidden_field :user_id, :value => current_user.id %>
<% if #pin.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#pin.errors.count, "error") %> prohibited this checkin from being saved:</h2>
<ul>
<% #pin.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<h3>Hi! Thank you for choosing to check-in with your teacher! This is a great way to get help, share your feelings and concerns, and make your school a safer place to learn. </h3>
<div class="form-group">
<%= label_tag(:classroom, "Select your classroom:") %>
<%= select_tag "pin[code]", options_from_collection_for_select(Classroom.all, "code", "code", ) %>
</div>
<h4>Where?</h4>
<% #causes.each do |cause| %>
<div class="checkbox">
<ul>
<li>
<%= check_box_tag "reflection[cause_ids][]", cause.id %>
<%= label_tag(cause.name) %>
</li>
<ul>
</div>
<% end %>
<div class="form-group">
<%= image_tag 'feelings.png', class: "image" %>
<h4>How are you feeling?</h4>
</div>
<% #emotions.each do |emotion| %>
<div class="checkbox">
<%= check_box_tag "pin[emotion_ids][]", emotion.id %>
<%= label_tag(emotion.name) %>
</div>
<% end %>
<div class="form-group">
<h4> You can <strong>free write </strong> </h4>
<p> I want my teacher to know _____________________________________.</p>
<%= f.text_area :question, class: "form-control" %>
</div>
<div class="form-group">
<h4> You can write about your own actions or thoughts here.</h4>
<p>Something I did was ________________________________.</p>
<%= f.text_area :question1, class: "form-control" %>
</div>
<div class="form-group">
<h4>You can write about the actions of another person here..</h4>
<p>Something __(name)_____did was___________________________________.</p>
<%= f.text_area :question2, class: "form-control" %>
</div>
<div class="form-group">
<h4>Do you have a question for your teacher?</h4>
<p>I want to ask my teacher ______________________________________.</p>
<%= f.text_area :question3, class: "form-control" %>
</div>
<div class="form-group">
<h4>Are you thinking about <strong>doing something else</strong>? You can write about it here.</h4>
<p>Something else I might do is ______________________________________.</p>
<%= f.text_area :question4, class: "form-control" %>
</div>
<div class="form-group">
<%= f.submit "submit", class: "btn btn-lg btn-primary" %>
</div>
<% end %>
EDIT [ ADDED pin_controller.rb]
class PinsController < ApplicationController
before_action :set_pin, only: [:show, :edit, :update, :destroy]
respond_to :html s
def home
#pins = Pin.all
respond_with(#pins)
authorize #pins
end
def show
respond_with(#pin)
end
def new
#pin = Pin.new
#emotions = Emotion.all
#causes = Cause.all
#school = School.find(params[:school])
respond_with(#pin)
authorize #pin
end
def edit
end
def create
code = params[:pin][:code]
#classroom = Classroom.where('code LIKE ?', code).first
unless #classroom
flash[:error] = "Classroom code incorrect"
#emotions = Emotion.all
#causes = Cause.all
render :new
else
params[:pin][:classroom_id] = #classroom.id
#pin = Pin.new(pin_params)
#pin.save
params[:pin][:cause_ids].each do |cause_id|
#cause = Cause.find(cause_id)
#pin.causes << #cause
end
params[:pin][:emotion_ids].each do |emotion_id|
#emotion = Emotion.find(emotion_id)
#pin.emotions << #emotion
end
if #pin.save
redirect_to signout_path and return
end
respond_with(#pin)
authorize #pin
end
end
def update
#pin.update(pin_params)
respond_with(#pin)
authorize #pin
end
def destroy
#pin.destroy
respond_with(#pin)
authorize #pin
end
private
def set_pin
#pin = Pin.find(params[:id])
authorize #pin
end
def pin_params
params.require(:pin).permit(:user_id, :question, :question1, :question2,
:question3, :question4, :question5, :classroom_id, :sad,
:happy, :mad, :brave, :embarrassed, :sorry, :frustrated,
:silly, :left_out, :excited, :hurt, :jealous, :confused,
:proud, :other)
end
end
Here's the exact error I'm getting
I've so far been unable to figure out the problem. What am I missing?
Stupid error but didn't catch it until I posted the form code... Thanks for the help!!
"reflection[cause_ids][]"
should be
"pin[cause_ids][]"
Thanks again for the help:)
<h4>Where?</h4>
<% #causes.each do |cause| %>
<div class="checkbox">
<ul>
<li>
<%= check_box_tag "reflection[cause_ids][]", cause.id %>
<%= label_tag(cause.name) %>
</li>
<ul>
</div>
<% end %>

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.

Solr not working Rails

I have this on my view:
<div class='container'>
<div class='row upper_container'>
<div class='search_container'>
<%= form_tag deals_path, :method => :get, :class => 'navbar-form navbar-left' do %>
<div class='form-group'>
<%= text_field_tag :search, params[:search], class: 'form-control' %>
</div>
<%= submit_tag 'Search', :name => nil %>
<% end %>
</div>
</div>
<% #deals.each_with_index do |d, i| %>
<% if i % 3 == 0 %>
<div class='row middle_container'>
<% end %>
<div class='col-md-4'>
<div class='deal_container'>
<%= d.title %>
<img src='<%= d.photo %>', class='deal_img'>
</div>
</div>
<% if (i % 3 == 2) || (i == (#deals.length - 1)) %>
</div>
<% end %>
<% end %>
</div>
this in my controller:
class DealsController < ApplicationController
def index
# #deals = Deal.paginate(:page => params[:page])
#search = Deal.search do
fulltext params[:search]
end
#deals = #search.result
end
private
def deal_params
params.require(:deal).permit(:title)
end
end
and this in my model:
class Deal < ActiveRecord::Base
searchable do
text :title
end
end
when I want to do a seach by some word, like 'Treatment', the #deals variable, in the controller is null, but the param is being sent: Parameters: {"utf8"=>"✓", "search"=>"Treatment"}
any idea?
Try this:
query = params[:search]
#search = Deal.search do
fulltext query
end
#deals = #search.result
Please check this answer for details.

Resources