0

In my controller i have the following

  def index
   if !params[:place_id].nil? || !params[:place_id].empty? 
    @restaurant = GoogleSearchedLocation.registered(params[:place_id])
   else
      redirect_to customers_url
    end
  end

While in my model I have the following scope defined

scope :registered , -> (place_id) { where(:place_id => place_id) }

Output is expected as below i.e in the form of array

< GoogleSearchedLocation id: 1, place_id: "ChIJSeoh6hkEGTkRsd0e1crAbHU", name: "Dunkin' Donuts", rating: 4.3, longitude: nil, latitude: nil, scope: "GOOGLE", created_at: "2015-10-15 10:59:23", updated_at: "2015-10-15 10:59:23">

I tried to convert it into object in my controller function like below

 @restaurant1= @restaurant[0].each_slice().map{|a| GoogleSearchedLocation.new(a)}

But it's throwing error

undefined method `each_slice' for < GoogleSearchedLocation:0x00000005345cb0>

Can anyone explain the reason for error while we all know the each_slice() function . And kindly suggest a reasonable way to convert this kind of array into object

3
  • 2
    @restaurant.first should give you the first object of ActiveRecord relation Commented Oct 15, 2015 at 12:25
  • Oops i didn't know the answer could be such a simple Commented Oct 15, 2015 at 12:27
  • :), just for clarity, I would use restaurants = GoogleSearchedLocation.registered(params[:place_id]) and @restaurant = restaurants.first, or something like that, coz your scope always returns a collection of objects and its better if your variable name to reflect that Commented Oct 15, 2015 at 12:28

1 Answer 1

2

You could simply use GoogleSearchedLocation.registered(params[:place_id]).first to take the first found record.


Also note that for such simple queries there are ActiveRecord helpers like find_by_something. Check out this:

@restaurant = GoogleSearchedLocation.find_by_place_id(params[:place_id])

P.S.

You could use params[:place_id].blank? in your condition:

nil.blank?
# => true

''.blank?
# => true 

'12'.blank?
# => false 
Sign up to request clarification or add additional context in comments.

1 Comment

actually it doesnt need to check at all, coz it always return an ActiveRecord relation even the id send as nil

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.