Question

I have the following before_save method:

def get_data
  url = "http://www.api-fetching-url.com/where_my_data_input_is=#{self.my_data}&output=json"
  new_data = HTTParty.get(url)
  @field_to_update = new_data['one']['two']['here']
  self.field_to_update = @field_to_update
end

Unfortunately, the self.my_data doesn't appear to be working, because the JSON url doesn't produce any result. But, when I substitute my_data in the hardcoded way, it works just fine. Moreover, I can do a find in the Rails console and get the my_data field just fine. So, it's not an issue with that field not saving or something on the form side.

Is there an issue inserting data this way in a before_save method? If not, is there a different way of doing this that I'm missing?

Was it helpful?

Solution

Some remarks:

  • You don't have to (and actually can't) always call methods with the self receiver. Private methods for example can only be called without an explicit receiver, so no self. for private methods...
  • Why don't you inspect the url and check whether it is correct? Just add puts url after the line where you assign the url, run your program and check the output. Is the url correct?
  • You probably use HTTParty not correctly: HTTParty.get('...') returns a response object and you probably have to parse the response's body properly.

An example for a JSON service:

url      = 'http://service.com/path/to/resource.json'
response = HTTParty.get url

data = JSON.parse(response.body)
# now you can use the data, e.g.
# bla = data['one']['foo']
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top