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?
Some remarks:
self
receiver. Private methods for example can only be called without an explicit receiver, so no self.
for private methods... puts url
after the line where you assign the url, run your program and check the output. Is the url correct? 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']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.