Jump to content

The ultimate community for Ruby on Rails developers.


Photo

NoMethodError in PinsController#index, undefined method `to_a' for #<Class:0x0000010150ec98>

ruby rails

  • Please log in to reply
3 replies to this topic

#1 spencerlong

spencerlong

    Passenger

  • Members
  • 1 posts

Posted 17 January 2014 - 05:43 AM

Hi there i'm getting this error and i can't seem to figure it out. Here's my controller, thanks.

 
class PinsController < ApplicationController
  before_action :set_pin, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!, except: [:index]
 
  def index
    @pins = Pin.to_a
  end
 
  def show
  end
 
  def new
    @pin = current_user.pins.build
  end
 
  def edit
  end
 
  def create
    @pin = current_user.pins.build(pin_params)
    if @pin.save
      redirect_to @pin, notice: 'Pin was successfully created.'
    else
      render action: 'new'
    end
  end
 
  def update
    if @pin.update(pin_params)
      redirect_to @pin, notice: 'Pin was successfully updated.'
    else
      render action: 'edit'
    end
  end
 
  def destroy
    @pin.destroy
    redirect_to pins_url
  end
 
  private
    # Use callbacks to share common setup or constraints between actions.
    def set_pin
      @pin = Pin.find(params[:id])
    end
 
    def correct_user
      @pin = current_user.pins.find_by(id: params[:id])
      redirect_to pins_path, notice: "Not authorized to edit this pin" if @pin.nil?
    end
 
    # Never trust parameters from the scary internet, only allow the white list through.
    def pin_params
      params.require(:pin).permit(:description, :image)
    end
end


#2 Bharat Soni

Bharat Soni

    Dispatcher

  • Members
  • 53 posts
  • LocationAhmedabad

Posted 17 January 2014 - 07:43 AM

Let me know Pin is your model name.


Fun with Ruby on Rails


#3 james

james

    Guard

  • Moderators
  • 221 posts
  • LocationLeeds, U.K.

Posted 17 January 2014 - 10:02 AM

The log file will tell you what line the error occurred on but you have in your index action

 

@pins = Pin.to_a

 

 

 

There is no class method called to_a on the class Pin

 

You probably meant to say

@pins = Pin.all

On another note you are mixing up your code a bit

 

You have in the correct_user method

@pin = current_user.pins.find_by(id: params[:id])

Yet you have in your set_pin method

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

You should pick one way or the other and stick to it. My recommendation is to go with the set_pin method as the find_by methods are being deprecated in favour of where methods.


Programming is just about problem solving!


#4 himanshu339

himanshu339

    Passenger

  • Members
  • 9 posts

Posted 17 March 2014 - 08:28 AM

Instead of Pin.to_a use Pin.all

 

This will return an array of all the records in pins table.

 

Hope this helps!







Also tagged with one or more of these keywords: ruby, rails

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users