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?
Related
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 %>
I've implemented a like/unlike function in my app. On the show page for an item, you can like/unlike without any issues. On a user's profile page though, where it lists all the foods they've uploaded, I have two issues: First, when I click the like button for one food, it triggers it for every food and then the button text under every food says "unlike this food", instead of only having the button text change for just the food that was clicked on. The like gets saved to the db for the correct food, but obviously I don't want the button text to change for foods that I haven't liked. Second, when I try to like a different food on the page without refreshing, the liked gets saved in the db as the original food that I clicked on, instead of the one I actually clicked on.
users.show.html.erb
<% #user.foods.each do |food| %>
<div class="row col-md-12">
<div class="food col-md-4">
<h3 class="title"><%= link_to food.title.capitalize, food_path(food.id) %></h3>
<%= link_to (image_tag (food.image.url)), food_path(food.id) %>
<%= render 'shared/vote_form', :food => food %>
<%= link_to pluralize(food.votes.count, "person"), user_votes_path(:user_id => current_user.id, :food_id => food.id) %> <%= food.votes.count == 1 ? 'wants' : 'want' %> to gobble this
</div>
<div class="description col-md-6">
<% if #user.id == current_user.id %>
<% if food.description.length == 0 %>
<p><%= link_to "Add Description", edit_food_path(food) %></p>
<% else %>
<p><%= food.description %><p>
<p><%= link_to "Edit Description", edit_food_path(food) %></p>
<% end %>
<% if food.recipe.length == 0 %>
<p><%= link_to "Add Recipe", edit_food_path(food) %></p>
<% end %>
<% else %>
<% if food.description.length == 0 %>
<p>No Description</p>
<% else %>
<p><%= food.description %><p>
<% end %>
<% if food.recipe.length == 0 %>
<p>No Recipe</p>
<% else %>
<p><%= link_to "View Recipe", food_path(food) %></p>
<% end %>
<% end %>
</div>
</div>
<% end %>
votes controller
class VotesController < ApplicationController
def index
#votes = Food.find(params[:food_id]).votes
end
def new
#vote = current_user.votes.new
end
def create
#user = current_user
#vote = current_user.votes.build(vote_params)
if #vote.save!
#food = #vote.food
respond_to do |format|
format.html {redirect_to :back, notice: "Liked!"}
format.js
end
puts #vote.food.id
else
puts "No"
redirect_back(fallback_location: root_path)
end
end
def show
#user = current_user
#vote = Vote.find(params[:id])
end
def destroy
#vote = Vote.find(params[:id])
#food = #vote.food
if #vote.destroy!
respond_to do |format|
format.html {redirect_to :back, notice: "Unliked!"}
format.js
end
else
puts "NOOOOOO"
end
end
private
def vote_params
params.require(:vote).permit(:food_id)
end
end
vote partial
<% unless current_user.votes.pluck(:food_id).include?(food.id) %>
<%= button_to "Like This Food", user_votes_path(current_user, { vote: { food_id: food.id } }), :remote => true %>
<% else %>
<% vote = food.votes.where(user_id: current_user.id).first %>
<%= button_to "Unlike This Food", user_vote_path(current_user, vote), :remote => true, method: "delete" %>
<% end %>
create.js.erb
$('.button_to').replaceWith("<%= j (render :partial => 'shared/vote_form', :locals => { :food => #food, :food_id => #food.id }) %>");
destroy.js.erb
$('.button_to').replaceWith("<%= j (render :partial => 'shared/vote_form', :locals => { :food => #food }) %>");
Take a look at your create.js.erb (destroy.js.erb has the same problem). You use select all elements with the class button_to - that is all buttons on the page. Then you call replaceWith that replaces all these buttons with the button provided as the argument. The result is that all buttons get replaced with the like button corresponding to the food you just liked. This is responsible for affecting all buttons on the page and making them refer the food you liked first.
The solution is to add an id attribute to the buttons that would include the ID of the food the button pertains to. For example, if Food with ID 1 is Lettuce then you need to add id="like-1" to the button and change $('.button_to') to $("#like-1").
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'
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.
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.