未定义的方法`id' for nil:NilClass - referential association - rails 4

时间:2016-12-30 17:15:21

标签: ruby-on-rails

有人可以建议我如何在我的控制器中定义@friend。我已将@friend定义为@friend = User.find_by_email(params[:id]),但这并没有被接受。如果有人能够解释我会非常感激

  

我目前收到此错误

undefined method `id' for nil:NilClass

enter image description here

视图/卡/ show.html.erb

  <div class="current_connection">
    <%= friendship_status(@user, @friend) %>
  </div>

在我的cards_controller.rb

class CardsController < ApplicationController
  before_action :set_card, only: [:show, :edit, :update, :destroy]
  before_filter :setup_friends

  def index
    ...
  end

  def show
  end

  def new
    ...
  end

  ...

  private
    def set_card
      @card = Card.find(params[:id])
    end

    def setup_friends
      @user = User.find(current_user.id)
      @friend = User.find_by_email(params[:id])
    end

    def card_params
      params.require(:card).permit(:title, :event_id)
    end
end

frienship_helper.rb

module FriendshipsHelper
  # Return an appropriate friendship status message.
  def friendship_status(user, friend)
    friendship = Friendship.find_by_user_id_and_friend_id(user.id, friend.id)
    return "#{friend.firstname} is not in your network (yet)" if friendship.nil?
    case friendship.status
    when 'requested'
      "#{friend.firstname} wants to connect with you"
    when 'pending'
      "You have requested to connect with #{friend.firstname}"
    when 'accepted'
      "#{friend.firstname} is in your network"
    end
  end
end

路由

Rails.application.routes.draw do

  devise_for :users
  resources :users do
    resources :events
  end

  resources :events do
    resources :cards
  end
end

2 个答案:

答案 0 :(得分:2)

似乎params[:id]并不包含用户的电子邮件,而是包含卡片的ID。请仔细检查您的参数。

如果User.find_by_email(params[:id])的任何用户都不存在,

nil将返回email == params[:id]

答案 1 :(得分:1)

@friend = User.find_by_email(此处插入电子邮件参数)。

@friend = User.find(params [:id])将返回一个User对象,如果它存在于数据库中,则其id等于params [:id]。

以下是如何使用find_by:http://apidock.com/rails/v4.0.2/ActiveRecord/FinderMethods/find_by 以下是使用find:http://apidock.com/rails/ActiveRecord/FinderMethods/find

的方法