Having problems setting a delete route - ruby-on-rails

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.

Related

How do I use a hidden_field_tag to help create a valid object in Ruby on Rails?

I'm creating a prayer website with the ability to comment on a public prayer. When I try to create a comment on a prayer, it returns four errors:
Prayer must exist
User must exist
User can't be blank
Prayer can't be blank
And then every comment creation form on the page is automatically filled in with the text I put in the first comment box, and all of them have the same 4 errors on them. I tried to use the hidden_field_tag to put in the comment form for the right user id and prayer id but they aren't put into the hash for the new comment object, they are separate.
This is the debug stuff at the bottom of the page:
#<ActionController::Parameters {"authenticity_token"=>"abcdefg", "comment"=>#<ActionController::Parameters {"content"=>"Comment comment 1 2 3"} permitted: false>, "user_id"=>"1", "prayer_id"=>"301", "commit"=>"Comment", "controller"=>"comments", "action"=>"create"} permitted: false>
controllers/static_pages_controller.rb
class StaticPagesController < ApplicationController
def home
if logged_in?
#prayer = current_user.prayers.build
#comment = current_user.comments.build
#feed_items = current_user.feed.paginate(page: params[:page])
end
end
end
controllers/comments_controller.rb
class CommentsController < ApplicationController
before_action :logged_in_user, only: [:create, :destroy]
before_action :correct_user, only: :destroy
def create
#comment = Comment.create(comment_params)
if #comment.save
flash[:success] = "Comment created!"
redirect_to root_url
else
#feed_items = current_user.feed.paginate(page: params[:page])
render 'static_pages/home', status: :unprocessable_entity
end
end
def destroy
#comment.destroy
flash[:success] = "Comment deleted"
redirect_back_or_to( root_url, status: :see_other )
end
private
def comment_params
params.require(:comment).permit(:content, :prayer_id, :user_id)
end
def correct_user
#comment = current_user.comments.find_by(id: params[:id])
redirect_to root_url, status: :see_other if #comment.nil?
end
end
models/comment.rb
class Comment < ApplicationRecord
belongs_to :prayer
belongs_to :user
default_scope -> { order( created_at: :desc) }
validates :user_id, presence: true
validates :prayer_id, presence: true
validates :content, presence: true, length: { maximum: 140 }
end
views/comments/_comment.html.erb
<li id="comment-<%= comment.id %>">
<%= link_to gravatar_for(comment.user, size: 30), comment.user %>
<span class="user"><%= link_to comment.user.name, comment.user %></span>
<span class="comment-content"><%= comment.content %></span>
<span class="timestamp">
Posted <%= time_ago_in_words(comment.created_at) %> ago.
<% if current_user?(comment.user) %>
<%= link_to "delete comment", comment, data: { "turbo-method": :delete,
"turbo-confirm": "Are you sure?"} %>
<% end %>
</span>
</li>
views/prayers/_prayer.html.erb
<li id="prayer-<%= prayer.id %>">
<%= link_to gravatar_for(prayer.user, size: 50), prayer.user %>
<span class="user"><%= link_to prayer.user.name, prayer.user %></span>
<span class="content">
<%= prayer.content %>
<% if prayer.image.attached? %>
<%= image_tag prayer.image.variant(:display) %>
<% end %>
</span>
<span class="timestamp">
Posted <%= time_ago_in_words(prayer.created_at) %> ago.
<% if current_user?(prayer.user) %>
<%= link_to "delete", prayer, data: { "turbo-method": :delete,
"turbo-confirm": "Are you sure?"} %>
<% end %>
</span>
<span>
<%= render 'shared/comment_form', prayer_id: prayer.id %>
</span>
<span>
<% if prayer.comments.any? %>
<ol class="comments">
<% prayer.comments.each do |comment| %>
<%= render comment %>
<% end %>
</ol>
<% end %>
</span>
</li>
** views/shared/_comment_form.html.erb * **
<%= form_with(model: #comment) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<center>
<div class="field">
<%= f.text_area(:content, placeholder: "Comment on this prayer...") %>
</div>
<div><%= hidden_field_tag :user_id, #user.id %></div>
<div><%= hidden_field_tag :prayer_id, prayer_id %></div>
<%= f.submit "Comment", class: "btn btn-primary" %>
</center>
<% end %>
views/shared/_error_messages.html.erb
<% if object != nil && 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 %>
views/shared/_feed.html.erb
<% if #feed_items.any? %>
<ol class="prayers">
<%= render #feed_items %>
</ol>
<%= will_paginate #feed_items,
params: { controller: :static_pages, action: :home } %>
<% end %>
With help from Maxence, I discovered I need to use f.hidden_field versus hidden_field_tag
so I changed the views/shared/_comment_form.html.erb to the following:
<%= form_with(model: #comment) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<center>
<div class="field">
<%= f.text_area(:content, placeholder: "Comment on this prayer...") %>
</div>
<div><%= f.hidden_field :user_id, value: #user.id %></div>
<div><%= f.hidden_field :prayer_id, value: prayer_id %></div>
<%= f.submit "Comment", class: "btn btn-primary" %>
</center>
<% end %>

<%= link_to 'Message me!', conversations_path(sender_id: current_user.id, recipient_id: user.id), method: 'post'%> not working

i'm new to rails and trying this for too long. I'm following tutorial to create simple chat feature for rails https://medium.com/#carly_l/how-to-build-a-simple-chat-messaging-system-in-rails-2958efcea047 , and I whenever I click new message it's not routing properly.
conversations.index.html.erb
<h3>Mailbox</h3>
<% #conversations.each do |conversation| %>
<% if conversation.sender_id == current_user.id || conversation.recipient_id == current_user.id %>
<% if conversation.sender_id == current_user.id %>
<% recipient = User.find(conversation.recipient_id) %>
<% else %>
<% recipient = User.find(conversation.sender_id) %>
<% end %>
<%= link_to recipient.first_name, conversation_messages_path(conversation)%>
<% end %>
<% end %>
</div>
</div>
All Users
<% #users.each do |user| %>
<% if user.id != current_user.id %>
<div class="item">
<%= user.first_name %> <%= link_to 'Message me!', conversations_path(sender_id: current_user.id, recipient_id: user.id), method: 'post'%>
</div>
<% end %>
<% end %>
**conversations index **
#users = User.all
#conversations = Conversation.all
conversations create function
def create
byebug
#user = current_user
if Conversation.between(params[:sender_id],params[:recipient_id]).present?
#conversation = Conversation.between(params[:sender_id], params[:recipient_id]).first
else
#conversation = Conversation.create!(conversation_params)
end
redirect_to conversation_messages_path(#conversation)
end
**routes.rb **
resources :conversations do
resources :messages
end
when I click message me path is
http://localhost:3000/conversations?recipient_id=1&sender_id=6
and does nothing.

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

Rails 4 acts_as_follower

I have two models
Users and Groups
a am using gem acts_as_follower
https://github.com/tcocca/acts_as_follower
User.rb
class User < ActiveRecord::Base
has_many :groups
acts_as_follower
end
and Group.rb
class Group < ActiveRecord::Base
belongs_to :user
acts_as_followable
end
links to follow and unfollow
<% if current_user %>
<% if current_user.following?(#group) %>
<h2> <%= link_to 'Unfollow', unfollow_group_path(#group), class: 'fa fa-pause' %></h2>
<% else %>
<h2> <%= link_to 'Follow', follow_group_path(#group), class: 'fa fa-play' %></h2>
<% end %>
<% else %>
<%= link_to 'Login or Register to Follow', user_session_path, class: 'fa fa-unlock' %>
<% end %>
link to administration group followers
<h5>followers
<%= p #group.followers.count %></h5>
<% #group.followers.each do |follower| %>
<%= link_to user_path(follower) do %>
<%= image_tag(follower.image.url(:show), size: "40x40") %>
<% if current_user.id == #group.user.id %>
<%= link_to 'Reject', unfollow_group_path(#group , user_id:follower.id), class: ' fa fa-close' , style: 'color:red;' %>
<% end %>
<% end %>
<% end %>
<% if current_user.id == #group.user.id %>
<h5>expect</h5>
<% #followers_block.each do |block| %>
<%= link_to user_path(block.follower) do %>
<%= image_tag(block.follower.image.url(:show), size: "40x40") %>
<%= link_to 'Accept', follow_group_path(#group , user_id:block.follower.id), class: ' fa fa-close' , style: 'color:red;' %>
<% end %>
<% end %>
<% end %>
groups_controller.rb
def follow
#group = Group.find(params[:id])
if params[:user_id] && #group.user_id == current_user.id
#user = User.find(params[:user_id])
#user_block = Follow.where(followable_id: #group, followable_type: "Group" , follower_id: #user ).first
#user_block.update_attribute(:blocked, false)
#user_block.save
redirect_to :back
else
if current_user
current_user.follow(#group)
flash[:notice] = 'are now following'
else
flash[:error] = "You must login to follow "
end
redirect_to :back
end
end
def unfollow
#group = Group.find(params[:id])
if params[:user_id] && #group.user_id == current_user.id
#user = User.find(params[:user_id])
#user.stop_following(#group)
redirect_to :back
else
if current_user
current_user.stop_following(#group)
flash[:notice] = 'You are no longer following .'
else
flash[:error] = 'You to unfollow #'
end
redirect_to :back
end
end
how to add parameter (:blocked, true) this
if current_user
current_user.follow(#group)
flash[:notice] = 'are now following'
or this
<h2> <%= link_to 'Follow', follow_group_path(#group), class: 'fa fa-play' %></h2>
solved
if current_user
follow = current_user.follow(#group)
follow.update blocked: true
flash[:notice] = 'are now following'

Method becomes nil after an ajax response?

The following code does the following: If the user, voted up show him a delete vote form and a vote down form. If the user voted down, show him a vote up form and the delete vote form. Otherwise just show the vote up and vote down form (I omitted some of the code so the question doesn't get too long).
(scenario: user voted down):
posts_controller.rb:
def show
#post = Post.find(params[:id])
#replies = #post.replies.paginate(page: params[:page])
#reply = #post.replies.build
#vote = Vote.new
store_location
end
votes_controller.rb:
class VotesController < ApplicationController
before_filter :signed_in_user
def create
#votable = find_votable
# Destroy the vote first in case the user already voted
if already_voted?
#vote = #votable.votes.find_by_user_id(current_user.id)
#vote.destroy
end
#vote = #votable.votes.build(params[:vote])
#vote.user_id = current_user.id
#votable.save
respond_to do |format|
format.html { redirect_back }
format.js
end
end
def destroy
#votable = find_votable
#vote = #votable.votes.find_by_user_id(current_user.id)
#vote.destroy
#votable.reload
respond_to do |format|
format.html { redirect_back }
format.js
end
end
private
def find_votable
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
nil
end
def already_voted?
#votable.votes.exists?(:user_id => current_user.id)
end
end
posts/vote_form
<div class="vote-form">
<% if #post.votes.exists?(:user_id => current_user.id) %>
<% if #post.votes.find_by_user_id(current_user.id).polarity == -1 %>
<%= form_for ([#post, #vote]), remote: true do |f| %>
<%= f.hidden_field :polarity, value: 1 %>
<div class="form-actions">
<%= button_tag type: :submit, class: "btn btn-small vote" do %>
<i class="icon-thumbs-down"></i> Vote up
<% end %>
</div>
<% end %>
<%= form_for ([#post, #post.votes.find_by_user_id(current_user.id)]),
method: :delete,
remote: true do |f| %>
<div class="form-actions">
<%= button_tag type: :submit, class: "btn btn-small btn-primary unvote" do %>
<i class="icon-thumbs-up"></i> Vote down
<% end %>
</div>
<% end %>
<% end %>
votes/create.js:
$('#<%= #votable.class.name.downcase %>-<%= #votable.id %> .vote-form').html(
"<%= escape_javascript(render('shared/delete_vote')) %>"
);
shared/_delete_vote.html.erb:
<% if #votable.votes.find_by_user_id(current_user.id).polarity == -1 %>
<%= form_for ([#votable, #votable.votes.new]), remote: true do |f| %>
<div class="form-actions">
<%= button_tag type: :submit, class: "vote-down btn btn-small" do %>
<i class="icon-thumbs-up"></i> Vote up
<% end %>
</div>
<% end %>
<%= form_for ([#votable, #vote]), method: :delete, remote: true do |f| %>
<div class="form-actions">
<%= button_tag type: :submit, class: "vote-up btn btn-small btn-primary" do %>
<i class="icon-thumbs-up"></i> Vote down
<% end %>
</div>
<% end %>
<% end %>
So, now everything works fine, except that I get this error when I click vote down, and then vote up right after (without refreshing the page):
ActionView::Template::Error (undefined method `polarity' for nil:NilClass):
1: <% if #votable.votes.find_by_user_id(current_user.id).polarity == 1 %>
2: <%= form_for ([#votable, #vote]), method: :delete, remote: true do |f| %>
What could be the problem?
EDIT:
I realized that the line in the error message is the problem (not #votable):
<% if #votable.votes.find_by_user_id(current_user.id).polarity == 1 %>
Strange, I thought it was the same as
<% if #post.votes.find_by_user_id(current_user.id).polarity == 1 %>
I think the problem is here:
def destroy
#votable = find_votable
#vote = #votable.votes.find_by_user_id(current_user.id)
#vote.destroy
#votable.reload
respond_to do |format|
format.html { redirect_back }
format.js
end
end
You destroy the vote for current user, so it can not be found inside view:
#votable.votes.find_by_user_id(current_user.id).polarity
That's why polarity is called on nil. You should reword the logic of your vote manipulations.
EDIT:
As the easiest solution, you may replace
if #votable.votes.find_by_user_id(current_user.id).polarity == -1
with
if #votable.votes.find_by_user_id(current_user.id).blank?

Resources