siuying / NanoStoreInMotion

RubyMotion wrapper for NanoStore, a lightweight schema-less key-value document database based on sqlite.
Other
103 stars 24 forks source link

Getting object by key #12

Closed tchukuchuk closed 12 years ago

tchukuchuk commented 12 years ago

Hi

I don't see how I can get objects by key. In fact I would like to use NanoStore with relationships, for example :

class Player < NanoStore::Model
  attribute :name
  attribute :created_at
end

class Game < NanoStore::Model
  attribute :name
end

class Participation < NanoStore::Model
  attribute :player_key
  attribute :game_key

  def player
    Player.find(:key => player_key).first
  end

  def game
    Game.find(:key => game_key).first
  end
end

player = Player.new(:name => 'julien')
player.save
game = Game.new(:name => 'game')
game.save
participation = Participation.new(:player_key => player.key, :game_key => game.key)
participation.save
participation.player # returns nil
participation.game # returns nil

The other way is to write something like this, but it may not be efficient :

class Participation
  def player
     Player.all.each { |pl| return pl if pl.key == player_key }
     nil
  end
end

Have you any suggestions ?

Best regards,

Julien

siuying commented 12 years ago

The finder will only work for non-key fields. Find by key is not implemented (yet).

It will need to do a search with key:

NSFNanoSearch *search = [NSFNanoSearch searchWithStore:nanoStore];
[search setKey:@"E01B4C77-B926-4807-AC76-7DCB728510C6"];
objects = [search searchObjectsWithReturnType:NSFReturnObjects error:nil];

in motion, it should be something like ...

search = NSFNanoSearch.searchWithStore(Player.store)
search.key = "E01B4C77-B926-4807-AC76-7DCB728510C6"
objects = search.searchObjectWithReturnType(NSFReturnObjects, error:nil)

Please see if that will work for you :)

mordaroso commented 12 years ago

Thanks @siuying. I had to fetch entries by keys too and your example worked for me (except for the small typo: searchObjectWithReturnType => searchObjectsWithReturnType).

It would be great to have a convenient finder method for this. Something like Player.find_by_key(key).

tchukuchuk commented 12 years ago

hi,

i have forked the project to add this feature.

regards,

julien

Le 28 août 2012 à 22:29, Fabio Kuhn notifications@github.com a écrit :

Thanks @siuying. I had to fetch entries by keys too and your example worked for me (except for the small typo: searchObjectWithReturnType => searchObjectsWithReturnType).

It would be great to have a convenient finder method for this. Something like Player.find_by_key(key).

— Reply to this email directly or view it on GitHub.