I am a begginer in Rails, im following code from a book and i am trying stuff to see if it breaks/works, anyway heres my UserControllers classUserController
class UsersController < ApplicationController
def new
#user = User.new
end
def edit
#user = User.find(params[:id])
end
def show
#user = User.find(params[:id])
end
def create
#user = User.new(params[:user])
if #user.save
redirect_to #user, :notice => 'Cadastro realizado'
else
render :new
end
end
end
And heres my show.html.erb
<p id="notice"><%=notice%></p>
<h2>Perfil: <%=#user.full_name %></h2>
<ul>
<li>Localização: <%= #user.location %> </li>
<li>Bio: <%= #user.bio %></li>
</ul>
<%= link_to 'Editar Perfil', edit_user_path(#user) %>
<%= link_to 'Mostrar Perfil', show_user_path(#user) %>
My problem is in the last line, when i try to acess this page i get a NomethodError,i am trying to understand why, why can i just change that to #user and the page works?
Try:
<%= link_to 'Mostrar Perfil', user_path(#user) %>
or even just
<%= link_to 'Mostrar Perfil', #user %>
In order to see how to name the routes, open a console and run
rake routes
Related
I'm currently working on a project involving users, likes, and posts. I have a like/unlike button that I finally got to work some of the time, but on certain user's profiles when I go to unlike a post, I get thrown this error, which says that it is coming from my destroy action in my likes controller:
ActionController::InvalidAuthenticityToken
I'm using devise, but don't know if that has to do with the cause of the issue.
Right now this is what I'm working with:
<h4>All of <%= #user.email %>'s posts:</h4>
<% #user.posts.order('created_at DESC').each do |post| %>
<li><%= post.content %></li>
<% unless current_user.likes.pluck(:post_id).include?(post.id) %>
<%= form_tag likes_path do %>
<%= hidden_field_tag 'post_id', post.id %>
<%= submit_tag "Like", :class => "like_button" %>
<% end %>
<% else %>
<% like = post.likes.where(user_id: current_user.id).first %>
<div class="unlike_button">
<%= form_tag like_path(like) do %>
<%= hidden_field_tag 'post_id', post.id %>
<%= button_to "Unlike", like_path(post), method: :delete %>
</div>
<% end %>
class LikesController < ApplicationController
def create
#post = Post.find(params[:post_id])
#like = Like.new(user_id: current_user.id, post_id: #post.id)
if #like.save
flash[:success] = "Post Liked!"
redirect_back(fallback_location: root_path)
else
flash[:notice] = "Couldn't like post"
redirect_back(fallback_location: root_path)
end
end
def destroy
#like = Like.find(params[:id])
#like.destroy
flash[:success] = "Post unliked"
redirect_back(fallback_location: root_path)
end
end
class PostsController < ApplicationController
def index
#posts = Post.all
#user = User.find(params[:user_id])
end
def new
#post = Post.new
#user = User.find(params[:user_id])
end
def create
#post = current_user.posts.build(post_params)
if #post.save
flash[:success] = "Posted!"
redirect_to user_path(current_user)
else
flash[:notice] = "Post could not be submitted"
redirect_to users_path
end
end
private
def post_params
params.require(:post).permit(:content)
end
end
There is a comment in application_controller.rb..
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
so ,you may try changing..
protect_from_forgery with: :exception
to this
protect_from_forgery with: :null_session
Hope it helps :)
I think I have figured it out.. At least have gotten it to work. I wasusing a form_for helper as well as button_to helper. I deleted the form_for helper and just stuck with
<%= button_to "Unlike", like_path(like), method: :delete %>
and it is now working
What helps me solve this problem is adding the Forward Slash in the URL
From:
= bootstrap_form_tag url: 'signup_with_phone' do |form|
To:
= bootstrap_form_tag url: '/signup_with_phone' do |form|
So I want to update an user in User table on the page and then when it's done, redirect to that user's page.
Whenever I do this, I get this error:
undefined method `name' for nil:NilClass
<% provide(:title, #user.name) %>
<p>
<%= #user.name %>
</p>
This is how my update looks like:
def update
#user = User.find(params[:id])
if #user.update_attributes(user_params)
flash[:success] = "Update successful"
redirect_to #user
else
render 'edit'
end
end
The page I redirect to:
<% provide(:title, #user.name) %>
<p>
<%= #user.name %>
</p>
What am I doing wrong here? Will provide more info if needed.
Edit:
Show action:
def show
if signed_in?
#user = User.find(params[:id])
end
end
I am trying to write a rails app and it keeps bombing on this one line of code in my controller.rb file:
posts GET /posts(.:format) posts#show
Can some one help me?
I am running ruby 1.9.3p429 (2013-05-15 revision 40747) [x86_64-darwin12.4.0]
with rails 3.2.13
UPDATE
I took out the line of code above and now I can't get rails to post the value (tag) of the selected check box. Can I get some guidance?
Here is my posts_controller.rb file:
class PostsController < ApplicationController
def new
end
def create
#post = Post.new(params[:post].permit(:check_box, :label))
#post.save
redirect_to #post
end
def show
#post = Post.find(params[:id])
end
def index
#posts = Post.all
end
private
def post_params
params.require(:post).permit(:check_box, :label)
end
end
Here is my new.html.erb file:
<h1>SWORD Mock Device Page</h1>
<%= form_for :post, url: posts_path do |f| %>
<p>
<h2>Android Phones</h2>
<%= f.check_box(:razr_max1) %>
<%= f.label(:razr_max1, "Droid Razr Max #1") %>
</p>
<p>
<%= f.check_box(:galaxyS2) %>
<%= f.label(:galaxyS2, "Samsung Galaxy S2") %>
</p>
<p>
<h2>Android Tablets</h2>
<%= f.check_box(:asusprime3) %>
<%= f.label(:asusprime3, "Asus Transormer Prime #3") %>
</p>
<p>
<%= f.check_box(:motoxoom1) %>
<%= f.label(:motoxoom1, "Motorola Xoom #1") %>
</p>
<p>
<%=f.submit "Select" %>
</p>
<% end %>
here is my routes.rb:
SWORDMockDev::Application.routes.draw do
resources :posts
root to: "landing#index"
end
and my show.html.erb:
<p>
<strong>Device:</strong>
<%= #post.title %>
</p>
Any help is greatly appreciated!!
Thanks!!
ironmantis7x
Instead of:
def create
#post = Post.new(params[:post].permit(:check_box, :label))
#post.save
redirect_to #post
end
You can do:
def create
#post = Post.new(post_params)
#post.save
redirect_to #post
end
The label is not going to submit in the post, only the value of the checkbox
I recommend you to use pry https://github.com/pry/pry and in the controller in the create you can do:
def create
binding.pry
#post = Post.new(post_params)
#post.save
redirect_to #post
end
And you can see what comes in the params, and what's going on. Also checkout your routes and see if everything is ok with:
rake routes
I'm new to Rails and I've been wandering aimlessly around stackoverflow trying to find a solution to my problem but can't seem to figure it out. I'm doing chapter 10 of Michael Hartl's tutorial and when I try to view the profile of a specific user the localhost:3000 page I get the following error messages:
"NoMethodError in Users#show"
followed by
"undefined method `name' for nil:NilClass".
The source is listed as the first line of my show.html.erb file but I can't see anything wrong with the code.
The home page works fine and the users index is viewable but beyond that it doesn't work. I understand that this could mean that the #user object is nil but I'm not sure how to fix this. My Rspec tests are also failing hard - any help would be greatly appreciated.
My users_controller.rb file:
class UsersController < ApplicationController
before_filter :signed_in_user, only: [:index, :edit, :update, :destroy]
# Arranges for a particular method to be called before the given actions.
before_filter :correct_user, only: [:edit, :update]
before_filter :admin_user, only: :destroy # Restricts the destroy action to admins.
def new
#user = User.new
end
def create
#user = User.new(params[:user])
if #user.save
sign_in #user
flash[:success] = "Welcome to the Sample App!"
redirect_to #user
else
render 'new'
end
end
def index
#users = User.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] = "Profile updated"
sign_in #user
redirect_to #user
else
render 'edit'
end
end
def destroy
User.find(params[:id]).destroy
flash[:success] = "User destroyed."
redirect_to users_url
end
private
# def signed_in_user
# unless signed_in?
# store_location
# redirect_to signin_url, notice: "Please sign in."
# end
# 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
def show
#user = User.find(params[:id])
#microposts = #user.microposts.paginate(page: params[:page])
end
end
My show.html.erb file:
<% provide(:title, #user.name) %>
<div class="row">
<aside class="span4">
<section>
<h1>
<%= gravatar_for #user %>
<%= #user.name %>
</h1>
</section>
</aside>
<div class="span8">
<% if #user.microposts.any? %>
<h3>Microposts (<%= #user.microposts.count %>)</h3>
<ol class="microposts">
<%= render #microposts %>
</ol>
<%= will_paginate #microposts %>
<% end %>
</div>
</div>
And users_helper.rb
module UsersHelper
# Returns the Gravatar (http://gravatar.com/) for the given user.
def gravatar_for(user, options = { size: 50 })
gravatar_id = Digest::MD5::hexdigest(user.email.downcase)
size = options[:size]
gravatar_url = "https://secure.gravatar.com/avatar/#{gravatar_id}?s=#{size}"
image_tag(gravatar_url, alt: user.name, class: "gravatar")
end
end
Here #user is nil. Because there is no record with the id (params[:id]). Thats why this error is coming.
<h1>
<%= gravatar_for #user %>
<%= !#user.nil? #user.name : "" %>
</h1>
It will check whether the #user having any record, if its having it will display it's name else it will display empty.
Your query doesn't find a user:
#user = User.find(params[:id])
does apparently return nil.
Please check that a user with the given ID exists. Additionally, you should make your actions fail safely when no object(s) are found:
<% if #user.nil? %>
<% provide(:title, 'Not found') %>
No user with that ID has been found.
<% else %>
<!-- Contents of your current show.html.erb -->
<% end %>
I used this code in my "users" views and had no trouble: <% if current_user.admin? %>. But using it in a set of views associated with a different controller throws up the "No method Error."
Background: the app allows admins to create scavenger hunts. Admins should be able to delete hunts. I thought I knew how to configure everything, but apparently, I'm missing something. Here's my code:
controller.rb
class HuntsController < ApplicationController
def index
#title = "All Hunts"
#hunts = Hunt.order("name ASC")
end
def show
#hunt = Hunt.find(params[:id])
#title = #hunt.name
end
def new
#hunt = Hunt.new
#title = "New Hunt"
end
def create
#hunt = Hunt.new(params[:hunt])
if #hunt.save
flash[:success] = "Hunt created!"
redirect_to hunts
else
#title = "New Hunt"
render 'new'
end
end
def edit
#hunt = Hunt.find(params[:id])
#title = "Edit hunt"
end
def delete
Hunt.find(params[:id]).destroy
flash[:success] = "Hunt destroyed."
redirect_to index
end
end
Views/Index.html.erb
<h1>All Hunts</h1>
<ul>
<% #hunts.each do |hunt| %>
<%= render hunt %>
<% end %>
</ul>
<%= link_to( "Create New Hunt", '/hunts/new') %>
Views/_hunt.html.erb
<li>
<%= link_to hunt.name, hunt %>
<% if current_user.admin? %>
<%= link_to "delete", hunt, :method => :delete, :confirm => "You sure?",
:title => "Delete #{hunt.name}" %>
<% end %>
</li>
Error Message when trying to head to /hunts:
NoMethodError in Hunts#index
Showing ...../app/views/hunts/_hunt.html.erb where line #3 raised:
undefined method `admin?' for nil:NilClass
current_user is nil, and thus does not know how to respond to admin?. Either ensure that current_user is always a user instance, or check that it's not nil.
In Ruby 2.3+, one can use the “safe navigation” operator (&.):
if current_user&.admin?
In Ruby 2.2 and earlier, instead use boolean short-circuiting:
if current_user && current_user.admin?
Note that ActiveSupport has try, but that has different behavior which will potentially hide bugs. For similar behavior, use try! instead.
Getting "undefined method _____ for nil:NilClass" is a very common occurrence in Ruby, so get used to it happening often :).
You have to sign in the user in order to instantiate current_user. If you are using devise, use:
class HuntsController < ApplicationController
before_filter :authenticate_user!
def index
...
end
.......
end
in your controller. And make sure that .admin? method is defined in your User model.