Newbie again in Rails. Following Michael Hartl's tutorial on rails and I'm trying to pass the last section and I get this error
undefined method `id' for #<String:0x3794b80>
It comes from my _feed_item.html.erb and I don't understand why I'm getting this error.
<li id="<%= feed_item.id %>">
<%= link_to gravatar_for(feed_item.user), feed_item.user %>
<span class="user">
<%= link_to feed_item.user.name, feed_item.user %>
</span>
<span class="content"><%= feed_item.content %></span>
<span class="timestamp">
Posted <%= time_ago_in_words(feed_item.created_at) %> ago.
</span>
<% if current_user?(feed_item.user) %>
<%= link_to "delete", feed_item, method: :delete, data: { confirm: "You sure?" }, title: feed_item.content %>
<% end %>
</li>
Hey guys, sorry I feel; asleep after.
When reviewing all my controllers I don't particularly see where it was defined however it did work before I started the last task so I don't know what happened in between.
Here is the user_controller
class UsersController < ApplicationController
before_filter :signed_in_user, only: [:index, :edit, :update]
before_filter :correct_user, only: [:edit, :update]
before_filter :admin_user, only: :destroy
def new
#user=User.new
end
def create
#user=User.new(params[:user])
if #user.save
#Handle a save
sign_in #user
flash[:success] = "Welcome to the Sample App!"
redirect_to #user
else
render 'new'
end
end
def show
#user=User.find(params[:id])
#microposts=#user.microposts.paginate(page: params[:page])
end
def edit
#user=User.find(params[:id])
end
def update
#user=User.find(params[:id])
if #user.update_attributes(params[:user])
flash[:success]="Successfully updated your profile"
sign_in #user
redirect_to #user
else
render 'edit'
end
end
def correct_user
#user=User.find(params[:id])
redirect_to(root_path) unless current_user?(#user)
end
def index
#users=User.paginate(page: params[:page])
end
def destroy
User.find(params[:id]).destroy
flash[:success]="User destroyed"
redirect_to users_url
end
def admin_user
redirect_to(root_path) unless current_user.admin?
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
micrpost_controller
class MicrpostsController< ApplicationController
before_filter :signed_in_user, only: [:create, :destroy]
def index
end
def create
#micropost=current_user.microposts.build(params[:micropost])
if #micropost.save
flash[:success]="Micropost Created!"
redirect_to root_url
else
#feed_items = []
render 'static_pages/home'
end
end
def destroy
#micropost.destroy
redirect_to root_url
end
def correct_user
#micropost=current_user.microposts.find_by_id(params[:id])
redirect_to root_url if #micropost.nil?
end
end
I got it to work people. The issues was in my micropost model.
def self.from_users_followed_by(user)
followed_user_ids= "SELECT followed_id FROM relationships WHERE follower_id=:user_id",
where("user_id IN (#{followed_user_ids}) OR user_id=:user_id", user_id: user)
end
should have been
def self.from_users_followed_by(user)
followed_user_ids= "SELECT followed_id FROM relationships WHERE follower_id=:user_id"
where("user_id IN (#{followed_user_ids}) OR user_id=:user_id", user_id: user.id)
end
Related
I'm at the end of a nested resource Rails app but I can't seem to figure out how to delete a review. I can delete an album just fine. My reviews belong to albums. Users have both albums and reviews.
I would also like to be able to make sure Users cannot delete reviews that they didn't write. I think that is where my error is coming from.
I keep getting this error:
ActiveRecord::RecordNotFound in AlbumsController#destroy
Couldn't find Album with 'id'=17
Extracted source (around line #57):
55
56
57
58
59
60
def set_album
#album = Album.find(params[:id])
end
def album_params
Here is my reviews controller:
class ReviewsController < ApplicationController
before_action :set_review, only: [:show, :delete, :edit, :update]
before_action :set_current_user, only: [:index, :new, :edit, :delete]
before_action :find_album, only: [:create, :edit]
before_action :must_login, only: [:index, :new, :create, :edit, :update, :delete]
def index
#albums = Album.with_recent_reviews
end
def show
##reviews = Review.where("album_id = ?", params[:album_id])
end
def new
if params[:album_id] && #album = Album.find_by(id: params[:client_id])
#review = #album.reviews.build
else
redirect_to albums_path
end
end
def create
#review = current_user.reviews.build(review_params)
#review.album = #album
if #review.save
redirect_to album_path(#album)
else
#album = #review.album
render :new
end
end
def edit
end
def update
if #review.update(review_params)
redirect_to album_path(params[:album_id])
else
render 'edit'
end
end
def destroy
if current_user.id == #review.user_id
#review.destroy
redirect_to album_path(params[:album_id])
else
flash[:error] = "Unable to delete your review. Please try again."
redirect_to album_reviews_path(#review)
##review.destroy
end
end
private
def set_review
#review = Review.find(params[:id])
end
def set_current_user
#user = current_user
end
def find_album
#album = Album.find(params[:album_id])
end
def review_params
params.require(:review).permit(:title, :date, :content, :user_id, :album_id, album_attributes:[:artist, :title, :user_id])
end
end
Here is my reviews index form where the delete link is located:
<% #albums.each do |album| %>
<br>
<br>
<% if album.avatar&.attached? %>
<image src="<%=(url_for(album.avatar))%>%" style="width:350px;height:350px;">
<% end %>
<br>
<%= album.artist %> - <%= album.title %>
<br>
<%= link_to "View Album", album_path(album) %>
<%= link_to "Edit Album", edit_album_path(album) %>
<br><br>
<% album.reviews.each do |review| %>
<% unless review.id.nil? %>
<small>Date written: <%= review.date %></small><br>
<small>Written by: <%= review.user.name %></small><br>
<strong>Title: <%= review.title %></strong><br>
Review: <%= review.content %><br>
<%= link_to "Edit Review", edit_album_review_path(album_id: album.id, id: review.id) %>
<%= link_to 'Delete', album_path(album_id: album.id, id: review.id), method: :delete, data: { confirm: 'Are you sure?' } %>
<br><br>
<% end %>
<% end %>
<br>
<% end %>
Albums controller:
class AlbumsController < ApplicationController
before_action :set_album, only: [:show, :edit, :update, :destroy]
before_action :must_login, only: [:new, :show, :create, :edit, :update, :destroy]
def index
#albums = Album.all
#user = current_user
end
def show
#review = #album.reviews.build
#review.user = current_user
# If you want to have some flag to indicate its status
##review.draft = true
#review.save
#reviews = Review.recent #scope
end
def new
#album = Album.new
#user = current_user
end
def create
#user = User.find(current_user.id)
#album = current_user.albums.build(album_params)
#album.user_id = current_user.id
if #album.save
redirect_to album_path(#album)
else
render :new
end
end
def edit
#user = current_user
end
def update
##album = current_user.albums.build(album_params)
#album.user_id = current_user.id
if #album.update(album_params)
redirect_to album_path(#album), notice: "Your album has been updated."
else
render 'edit'
end
end
def destroy
#album.delete
redirect_to albums_path
end
private
def set_album
#album = Album.find(params[:id])
end
def album_params
params.require(:album).permit(:artist, :title, :avatar, :user_id, review_attributes:[:title, :date, :content, :user_id, :album_id])
end
end
You have this issue because you are not passing an album_id to the destroy action of the review controller. The reason you need an album_id is because your routes probably look like this (since you said they were nested):
http://localhost:3000/albums/1/reviews
You can see in your route that you need an album_id (the 1 after the album). Try changing your review destroy action to this:
def destroy
if current_user.id == #review.user_id
#album.reviews.find(params[:id]).destroy
redirect_to album_path(params[:album_id])
else
flash[:error] = "Unable to delete your review. Please try again."
redirect_to album_reviews_path(#review)
end
end
You'll also have to change your before_action in the review controller to this, since you need the album_id to destroy the review:
before_action :find_album, only: [:create, :update, :destroy]
I am building an app for practice,(Instagram replica), and I am having a really hard time getting a feature to work.
What I want to happen is, a user is able to edit or delete their own comments about a picture. I was able to get the delete feature to work, but I am unable to figure out the 'Edit comment' feature. I want the user to be able to edit the comment from within the picture show page. Code is below.
pics_controller.rb
class PicsController < ApplicationController
before_action :find_pic, only: [:show, :edit, :update, :destroy, :upvote]
before_action :authenticate_user!, except: [:index, :show]
before_action :require_same_user, only: [:edit, :update, :destroy]
def index
#pics = Pic.all.order("created_at DESC")
end
def show
end
def new
#pic = current_user.pics.build
end
def create
#pic = current_user.pics.build(pic_params)
if #pic.save
redirect_to #pic, notice: "Your pic has been posted!"
else
render :new
end
end
def edit
end
def update
if #pic.update(pic_params)
redirect_to #pic, notice: "Awesome! Your Pic was updated!"
else
render :edit
end
end
def destroy
if #pic.destroy
redirect_to root_path
end
end
def upvote
#pic.upvote_by current_user
redirect_back fallback_location: root_path
end
private
def pic_params
params.require(:pic).permit(:title, :description, :image)
end
def find_pic
#pic = Pic.find(params[:id])
end
def require_same_user
if current_user != #pic.user
flash[:danger] = "You can only edit or delete your own pictures"
redirect_to root_path
end
end
end
comments_controller.rb
class CommentsController < ApplicationController
def create
#pic = Pic.find(params[:pic_id])
#comment = #pic.comments.create(params[:comment].permit(:name, :body))
redirect_to pic_path(#pic)
end
def edit
#pic = Pic.find(params[:pic_id])
#comment = #pic.comments.find(params[:id])
redirect_to #pic
end
def update
#comment = #pic.comments.find(params[:id])
#comment.update_attributes(comment_params)
if #comment.save
redirect_to #pic
end
end
def destroy
#pic = Pic.find(params[:pic_id])
#comment = #pic.comments.find(params[:id])
#comment.destroy
redirect_to pic_path(#pic)
end
def show
#pic = Pic.find(params[:pic_id])
end
private
def comment_params
params.require(:comment).permit(:body)
end
end
And here is the (_comment.html.erb) partial being called from the show page
<div class="card" style="width: 18rem;">
<div class="card-header">
<span class="badge badge-dark"><%= comment.name %></span>
</div>
<ul class="list-group list-group-flush">
<p><%= comment.body %></p>
</ul>
</div>
<% if user_signed_in? && comment[:body].present? %>
<p><%= link_to 'Delete Comment', [comment.pic, comment], method: :delete, class: "btn btn-danger",
data: { confirm: "Are you sure?" } %></p>
<p><%= link_to 'Edit Comment', edit_pic_comment_url(#pic, comment), class: 'btn btn-primary' %></p>
<% end %>
Any help is greatly appreciated. TIA
You need to ajaxify for that scenario. The steps will be:
Create the edit link with data-remote=true option. It'll enable the link to hit on the server with a ajax request. Also, add a editable div.
Edit
<div id="comment_#{comment.id}_form"></div>
In the edit method respond the request using js. Like:
def edit
respond_to do |format|
format.js # actually means: if the client ask for js -> return edit.js
end
end
Create edit.js file. In there, render the comment _form.html.erb on the defined div with ID - comment_4_form (Lets assume you're now editing comment with id 4).
It's not elaborated I know. The solution will be much bigger if I elaborate. But you are good to go if you understand the cycle.
I've read other SO articles relating to UrlGenerationError's which seem to point to singularization or plurization of a word, but I don't think that's the issue here.
It works when I remove from valuations/_form.html.erb:
<%= render "comments/comments" %>
<%= render "comments/form" %>
Submit the _form with :name & :tag_list, readd
<%= render "comments/comments" %>
<%= render "comments/form" %>
and then refresh. What's the deal when nil?
routes
resources :valuations do
resources :comments
end
comments_controller
class CommentsController < ApplicationController
before_action :load_commentable
before_action :set_comment, only: [:show, :edit, :update, :destroy]
before_action :logged_in_user, only: [:create, :destroy]
def index
#comments = #commentable.comments
end
def new
#comment = #commentable.comments.new
end
def create
#comment = #commentable.comments.new(comment_params)
if #comment.save
#comment.create_activity :create, owner: current_user
redirect_to #commentable, notice: "comment created."
else
render :new
end
end
def edit
#comment = current_user.comments.find(params[:id])
end
def update
#comment = current_user.comments.find(params[:id])
if #comment.update_attributes(comment_params)
redirect_to #commentable, notice: "Comment was updated."
else
render :edit
end
end
def destroy
#comment = current_user.comments.find(params[:id])
#comment.destroy
#comment.create_activity :destroy, owner: current_user
redirect_to #commentable, notice: "comment destroyed."
end
private
def set_comment
#comment = Comment.find(params[:id])
end
def load_commentable
resource, id = request.path.split('/')[1, 2]
#commentable = resource.singularize.classify.constantize.find(id)
end
def comment_params
params.require(:comment).permit(:content, :commentable)
end
end
valuations_controller
class ValuationsController < ApplicationController
before_action :set_valuation, only: [:show, :edit, :update, :destroy]
before_action :logged_in_user, only: [:create, :destroy]
def index
if params[:tag]
#valuations = Valuation.tagged_with(params[:tag])
else
#valuations = Valuation.order('RANDOM()')
end
end
def show
#valuation = Valuation.find(params[:id])
#commentable = #valuation
#comments = #commentable.comments
#comment = Comment.new
end
def new
#valuation = current_user.valuations.build
#commentable = #valuation
#comments = #commentable.comments
#comment = Comment.new
end
def edit
end
def create
#valuation = current_user.valuations.build(valuation_params)
if #valuation.save
redirect_to #valuation, notice: 'Value was successfully created'
else
#feed_items = []
render 'pages/home'
end
end
def update
if #valuation.update(valuation_params)
redirect_to #valuation, notice: 'Value was successfully updated'
else
render action: 'edit'
end
end
def destroy
#valuation.destroy
redirect_to valuations_url
end
private
def set_valuation
#valuation = Valuation.find(params[:id])
end
def correct_user
#valuation = current_user.valuations.find_by(id: params[:id])
redirect_to valuations_path, notice: "Not authorized to edit this valuation" if #valuation.nil?
end
def valuation_params
params.require(:valuation).permit(:name, :private_submit, :tag_list, :content, :commentable, :comment)
end
end
comments/_form.html.erb
<%= form_for [#commentable, #comment] do |f| %>
<% if #comment.errors.any? %>
<div class="error_messages">
<h2>Please correct the following errors.</h2>
<ul>
<% #comment.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="america">
<div class="form-group">
<%= f.text_area :content, rows: 4, class: 'form-control', placeholder: 'Enter Comment' %>
</div>
<div class="america2">
<%= button_tag(type: 'submit', class: "btn") do %>
<span class="glyphicon glyphicon-plus"></span> Comment
<% end %>
</div>
<% end %>
Thank you so much for your time.
When you have a nested resource like that, the url for creating a comment looks like /valuations/123/comments where 123 is the id of the valuation - without a valuation id this url cannot be generated.
On your Valuations#new page, the valuation (i.e. #commentable) is an unsaved object, so it has no id yet, hence the error about a missing valuation_id. In addition having one form nested within another is invalid html and will lead to odd behaviour. On your show page on the other hand, the valuation does have an id and so things should work as they are.
If you want to create a valuation and its initial comment(s) in one go then you should use accepts_nested_attributes_for and fields_for to add the fields for the comments to your valuation form (There are other ways, but accepts_nested_attributes_for is what is built into rails)
I have two classes of users: "users" and "shops". I want the admin to be a "user" and be able to delete shops, and am running in to trouble.
I was able to get the delete button to show up in shops/index.html.erb if the logged in user was an admin (shown below), but when I try to delete a shop object I get the error The action 'destroy' could not be found for ShopsController
shops/index.html.erb
<% provide(:title, 'All shops') %>
<h1>All Shops</h1>
<ul class="center hero-unit col-md-6 col-md-offset-3 shops">
<% #shops.each do |shop| %>
<li>
<div class= "shop-name pull-left">
<%= link_to shop.name, shop %>
<% if current_user.admin? && !current_shop?(shop) %>
| <%= link_to "(Delete Shop)", shop, method: :delete,
data: { confirm: "You sure?" } %>
<% end %>
</div>
<div class= "shop-address pull-right">
<p><%= shop.address %> <br> <%= shop.city %>, <%= shop.state %> <%= shop.zip %> <br> <%= shop.phone %></p>
</div>
</li>
<% end %>
</ul>
The destroy action is in the shops controller though:
class ShopsController < ApplicationController
before_action :logged_in_shop, only: [:edit, :update]
before_action :logged_in_user, only: :destroy
before_action :correct_shop, only: [:edit, :update]
before_action :admin_user, only: :destroy
def index
#shops = Shop.all
end
def show
#shop = Shop.find(params[:id])
end
def new
#shop = Shop.new
end
def create
#shop = Shop.new(shop_params)
if #shop.save
shop_log_in #shop
flash[:success] = "Thank you for signing up, welcome to ensage!"
redirect_to shop_home_path
else
render 'new'
end
end
def edit
#shop = Shop.find(params[:id])
end
def update
#shop = Shop.find(params[:id])
if #shop.update_attributes(shop_params)
flash[:success] = "Profile updated"
redirect_to #shop
else
render 'edit'
end
end
def destroy
Shop.find(params[:id]).destroy
flash[:success] = "Shop deleted"
redirect_to shops_url
end
private
def shop_params
params.require(:shop).permit(:name, :address, :city, :state, :zip, :email, :phone, :password,
:password_confirmation, :picture)
end
def correct_shop
#shop = Shop.find(params[:id])
redirect_to(root_url) unless current_shop?(#shop)
end
def admin_user
redirect_to(root_url) unless current_user.admin?
end
end
How can I allow an admin user to delete a shop?
You have set your destroy method as private, so it is not accessible.
before_action :logged_in_shop, only: [:edit, :update, :destroy]
You probably want to remove :destroy from here, or it will expect that you are logged in as shop in order to destroy it. I'm not sure how your access control works but be careful not to make this publicly accessible.
You have put action destroy in private section, this is why it is invisible. Try moving it up over private keyword
First move destroy action out of private, secondly I cannot see admin_shop method anywhere, either remove this line or define admin_shop method
before_action :admin_shop, only: :destroy
To add admin_shop method
def admin_shop
unless current_user.admin?
flash[:error] = "Not authorized"
redirect_to shops_url
end
end
In your destroy action
def destroy
user = User.find(current_user.id)
Shop.find(params[:id]).destroy
sign_in user, bypass: true
flash[:success] = "Shop deleted"
redirect_to shops_url
end
I've got a team members page which pulls through the users associated with a university sports club, I'm trying to get it to produce a check box next to each member so that a member of the committee can simply select several members and on pressing a submit button the system will send an email to them.
I tried <%= check_box_tag(<%= render #users %>) %> but didn't have any luck
show_selection.html.rb - This is the page that renders the users
<% if signed_in? %>
<% if current_user.captain? %>
Welcome, select members to send a message to below
<table summary="Team members">
<tr>
<td class="main">
<% unless #users.empty? %>
<ul class="users">
<%= render #users %>
</ul>
<%= will_paginate #users %>
<% end %>
</td>
</tr>
</table>
<br>
<br>
<% else %>
<h1>An error has occured</h1>
<br>
<p>It looks like you're trying to access a restricted page <%= link_to "Please Click Here", '/' %> </p>
<% end %>
<% else %>
An error has occured
<br>
<p>It looks like you're trying to access a restricted page <%= link_to "Please Click Here", '/' %> </p>
<% end %>
users_contorller.rb
class UsersController < ApplicationController
before_filter :authenticate, :only => [:index, :edit, :update, :destroy]
before_filter :correct_user, :only => [:edit, :update]
before_filter :admin_user, :only => :destroy
def show
#user = User.find(params[:id])
#microposts = #user.microposts.paginate(:page => params[:page])
#title = #user.name
#admins = User.where(:admin => "t")
#captains = User.where(:captain => "t")
#clubs = User.where(:captain => "t")
end
def new
#user = User.new
#title = "Sign up"
end
def create
#user = User.new(params[:user])
if #user.save
sign_in #user
flash[:success] = "Welcome to University Sports!"
redirect_to #user
UserMailer.welcome_email(#user).deliver
else
#title = "Sign up"
render 'new'
end
end
def edit
#title = "Edit user"
end
def update
#user = User.find(params[:id])
if #user.update_attributes(params[:user])
flash[:success] = "Profile updated."
redirect_to #user
else
#title = "Edit user"
render 'edit'
end
end
def index
#users = User.paginate(:page => params[:page])
end
#def admins
# #users = User.admins
# render "users/index"
#end
def admins
#admins=User.where(:admin => "t")
end
def captains
#captains=User.where(:captain => "t")
end
def clubs
#clubs=User.where(:captain => "t")
end
def destroy
User.find(params[:id]).destroy
flash[:success] = "User destroyed."
redirect_to users_path
end
def following
#title = "Following"
#user = User.find(params[:id])
#users = #user.following.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
def selection
#title = "Selection"
#user = User.find(params[:id])
#users = #user.followers.paginate(:page => params[:page])
render 'show_selection'
end
private
def authenticate
deny_access unless signed_in?
end
def correct_user
#user = User.find(params[:id])
redirect_to(root_path) unless current_user?(#user)
end
def admin_user
redirect_to(root_path) unless current_user.admin?
end
end
Firstly you will need to wrap this in a form to handle the submission of the selected members to email. The form should be posted to a mailer controller or an action to handle the selected members for emailing.
<%= render #users %>
This will render a partial for each of the objects inside #users. You should add the checkbox inside this partial in order to render it for each member.
You will have something like this in your partial
<%= check_box_tag "user_ids[]", user.id %>
Ryan has a railscast that will point you out the in right direction of how to implement. This is about updating the records, but you can modify the code to work with your scenario.
http://railscasts.com/episodes/52-update-through-checkboxes