简体   繁体   中英

How to get push value key in Firebase Ruby REST wrapper

I am working on a project to do CRUD Operations to firebase. I made use of this to help facilitate and link my ruby project to firebase.

Functions:

def delete_firebase(event_params,rootpath="Events/")
  query = init_firebase.delete(rootpath,event_params)
end

def new_firebase(event_params,rootpath="Events")
  query = init_firebase.push(rootpath,event_params)
end

def init_firebase # Inits firebase project with URL and secret
  firebaseURL = "myfirebaseprojecturl"
  firebaseSecret = "myfirebasesecret"
  firebase = Firebase::Client.new(firebaseURL, firebaseSecret)
end

Event params consist of my event parameters as shown below

def event_params
  params.require(:event).permit(:eventID, :eventName, :attachment, :eventNoOfPpl, :eventAdminEmail, {eventpics: []})
end

I encountered an issue. When I push with push() into firebase, there is a random key like -LSFOklvcdmfPOWrxgBo . In such case, the structure of the document would look like this:


But I cannot delete anything from -LSFOklvcdmfPOWrxgBo as I do not have the value. I used delete() from Oscar's firebase-ruby gem. I would appreciate any help with this issue.

I re-read the gem docs, and got some help from my friends and came up with two solutions

  1. The body's response has response.body # => { 'name' => "-INOQPH-aV_psbk3ZXEX" } and thus, you're able to find out the name if you'd like
  2. Change the index, and don't use .push , instead I made use of .set and did a random number for every event

Final solution

  def load_firebase(root_path = "Events")
    firebase_json = init_firebase.get(root_path)
    if valid_json?(firebase_json.raw_body)
      @json_object = JSON.parse(firebase_json.raw_body)
    end
  end

  def update_firebase(event_params, root_path = "Events/")
    init_firebase.update("#{root_path}#{event_params["eventID"]}", event_params)
  end

  def delete_firebase(event_params, root_path = "Events/")
    init_firebase.delete("#{root_path}#{event_params["eventID"]}")
  end

  def save_firebase(event_params, root_path = "Events/")
    init_firebase.set("#{root_path}#{event_params["eventID"]}", event_params)
  end

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM