undefined method `permit' for #<String:0x007f66ec6ff180> ruby on rails

谁说胖子不能爱 提交于 2019-12-25 18:25:46

问题


I read many links specially on stackoverflow but could not find the solution as there was some difference . so I want to make my point clear as explained below:

I have an ajax call pointing to my controller and it has only one parameter google_searched_locations , which is basically contains json string

google_searched_locations      [{"geometry":{"location":{"J":31.482273,"M":74.33069999999998}},"icon":"https://maps.gstatic.com/mapfiles
/place_api/icons/restaurant-71.png","id":"b93a99a46343de01d0d928f99470f9b0f5f6f11d","name":"Dunkin' Donuts"
,"place_id":"ChIJSeoh6hkEGTkRsd0e1crAbHU","rating":4.3,"reference":"CnRhAAAA4x8yMjf9__CURWmYX6ojnpgu
-M1aL4Cvsmp6j2nKOLiqlBRlslTtPU8hUc6tJWAehCE967tW8Z623new_ivN8_PWbypr6ANDj_6AIxxGTQcwneyfHCigsHWhcdrUlcJAsQTycbHOTdmu6n8loZiU-hIQHNPqBNJRlho9fVjRfomU-BoUcdX_NGHhBFs_pxQiPZTlUD-W88o"
,"scope":"GOOGLE","types":["restaurant","food","point_of_interest","establishment"],"vicinity":"Lahore"
,"html_attributions":[]}]

my action contains the following code

 def searchResults

  @restaurant = GoogleSearchedLocation.new(params_google_searched_locations)
  byebug
  if @restaurant.save!
    render json: { :status => :Ok }  
  else
      render json: { :status => :failed }
  end
end

And code in params_google_searched_locations is as follows

def params_google_searched_locations
 params.require(:google_searched_locations).permit(:place_id)
 end

Now the whole ajax call fails throwing the following error in response

NoMethodError in GoogleSearchedLocationController#searchResults

undefined method `permit' for #< String:0x007f66ec5515b8 >

Solution with the reason will be more appreciated . Thanks in advance


回答1:


Usually, you would use a combination of permit/require on params where the parent returns a hash e.g. {user: {name: 'Maria'}.

However, the parent returns a JSON string. So what you would do is parse that JSON and then use the permit. However, keep in mind that you have just lost the indifference access from Rails where you can access a key using a symbol or a string

However, from your example since the JSON returns an array, I don't think you can use permit.

If it was a hash, I believe you could do

def params_google_searched_locations json = params.require(:google_searched_locations) {place_id: JSON.parse(json).permit(:place_id)} end

At any case, you don't necessarily need to use permit. You can whitelist the params yourself.



来源:https://stackoverflow.com/questions/33016156/undefined-method-permit-for-string0x007f66ec6ff180-ruby-on-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!