开发者

undefined method `name' for nil:NilClass

I am trying to find users in "show" action of my "Users" controller using email. Where i am getting this error.

NoMethodError in UsersController#show
  undefined method `name' for nil:NilClass

Now i am using singular resource routes as without singular resource i was getting error like

Routing Error
 No route matches {:action=>"show", :controller=>"users", :id=>#<User name: "sandip", email: "sandip@example.com", address: nil, encrypted_password: "605b20529364629b7668d55006310536", created_at: "2011-10-07 04:23:23", updated_at: "2011-10-07 04:23:23">}

Now my routes.rb file looks like this.

Demo::Application.routes.draw do
  resource :user
  resources :sessions, :only => [:new, :create, :destroy]

  match '/signout', :to => 'sessions#destroy'
  match 'user/:email', :to => 'users#show'
  root :to => "sessions#new"
end

With this routes the "Routing Error" is gone but a new "NoMethodError" error has come up.

My user controller( only question related part)

class UsersController < ApplicationController

  def show      
    @user = User.find_by_email(params[:email]) if params[:email].present?
    @title = @user.name
  end
end

In order to find user using email i have added a method in my user model.

My user model(only question related part)

class User < ActiveRecord::Base
   def to_param  # overridden
     "#{email}"
   end
end

Now when a user Sign In, the url on the browser comes l开发者_StackOverflowike this.

http://localhost:3000/user?format=sandip%40example.com

and i get "NoMethodError" error. But when i manually change "format" to "email" on the url , everything works fine.

http://localhost:3000/user?email=sandip%40example.com 

How can i get "email" instead of "format" on the url ? Can somebody help please.


Routes mapping shows

match 'user/:email', :to => 'users#show'

so the url that would work for you is like

http://localhost:3000/user/sandip%40example.com 

where email param would be set to sandip%40example.com

However, using the url pattern as above may not be recommended.

Also, it also seems the input element name in you sign up erb/haml is "format" and should be changed to "email" for it to be passed as an url parameter.

http://localhost:3000/user?email=sandip%40example.com 

works cause you are passing the email parameter explicitly

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜