PinsController中的Rails Beginner NoMethodError #new

时间:2016-04-25 02:31:34

标签: ruby-on-rails ruby ruby-on-rails-3

有问题不断获取错误未定义方法`pin'为nil:NilClass,有人可以解释如何修复此错误。按照教程进行操作,最近遇到了困难。

pins_controller.rb

class PinsController < ApplicationController
    before_action :find_pin, only: [:show, :edit, :update, :destroy]


    def index
        @pins = Pin.all.order("created_at DESC")
    end

    def new
        @pin = current_user.pins.build
    end


    def create
        @pin = current_user.pins.build(pin_params)

        if @pin.save
            redirect_to @pin, notice: "Successfully created new Pin"
        else
            render 'new'
        end
    end

    def edit

    end

    def update
        if @pin.update(pin_params)
            redirect_to @pin, notice: "Pin was Successfully updated!"
        else
            render 'edit'
        end
    end


    def destroy
        @pin.destroy
        redirect_to root_path
    end


    private

    def pin_params
        params.require(:pin).permit(:title, :description)
    end

    def find_pin
        @pin = Pin.find(params[:id])
    end
end

user.rb

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
    has_many :pins     
end

pin.rb

class Pin < ActiveRecord::Base
    belongs_to :user
end

的routes.rb

Rails.application.routes.draw do
  devise_for :users
resources :pins

root "pins#index"
end

2 个答案:

答案 0 :(得分:1)

如果您正在使用设计,则可能需要添加 struct TEST *test_struct, *test_int; test_struct = malloc(sizeof(struct TEST)); test_struct->uni = malloc(sizeof(struct TEST)); // uni should be allocated with size of the union, not the struct test_struct->uni->fill->name = NULL; // uni->fill is a pointer to struct FILL, it should be allocated too before accessing its members test->struct->uni->fill->id = 5; test_int = malloc(sizeof(int)); // test_int is of type struct TEST, you are allocating a integer here test_int->uni->type = 10; // same, uni not allocated 引脚控制器内部的方法,确保用户登录。

答案 1 :(得分:1)

如果您使用的是gem Devise,那么帮助方法current_user会在您的会话中返回当前登录的用户。

请确保用户已登录/

您可以通过在应用程序控制器中添加before_action :authenitcate_user!来确保用户已登录(适用于您应用程序中的所有操作)。