no method error - undefined method

23 views
Skip to first unread message

Fatima Fatima

unread,
Sep 1, 2014, 6:27:23 PM9/1/14
to rubyonra...@googlegroups.com
I thought I had defined the method, but I keep getting an error. Should
I just be able to call user.favorite_places? Would appreciate any
help.

favorite_places_controller.rb

class FavoritePlacesController < ApplicationController

before_action :set_place, except: [:index]
before_action :authenticate_user!



def index
@places = User.favorite_places
end

def create
if Favorite.create(favorited: @place, user: current_user)
redirect_to @place, notice: 'Place has been favorited'
else
redirect_to @place, alert: 'Something went wrong. *womp womp*'
end
end

def destroy
Favorite.where(favorited_id: @place.id, user_id:
current_user.id).first.destroy
redirect_to @place, notice: 'Place is no longer a favorite'
end



private



def set_place
@place = Place.find(params[:place_id] || params[:id])
end

end


Favorite.rb
class Favorite < ActiveRecord::Base
belongs_to :user
belongs_to :favorited, polymorphic: true
belongs_to :place

end

user.rb

class User < ActiveRecord::Base


#Relationships

#Favorites
has_many :favorites
has_many :favorite_places, through: :favorites, source: :favorited,
source_type: 'Place'

end

--
Posted via http://www.ruby-forum.com/.

Dave Aronson

unread,
Sep 1, 2014, 7:31:33 PM9/1/14
to rubyonra...@googlegroups.com
On Monday, September 1, 2014, Fatima Fatima wrote:

I thought I had defined the method, but I keep getting an error.  Should
I just be able to call  user.favorite_places?  Would appreciate any
help.
...
  def index
     @places = User.favorite_places
  end

Is this where it's blowing up?  You're using it like a class method there, when most likely you've defined it as an instance method.  Glancing at the rest, I think you meant current_user.favorite_places.

-Dave the Codosaurus


--
Sent from Gmail Mobile; please excuse top posting, typos, etc. :-(

Fatima Fatima

unread,
Sep 2, 2014, 6:45:31 PM9/2/14
to rubyonra...@googlegroups.com
Thanks Dave, yes, you're right. Changed that part to:

def index
@places = current_user.favorite_places.all
end

Fixed the rest via making only favorite polymorphic, not
favorite_places.
Reply all
Reply to author
Forward
0 new messages