maglev icon indicating copy to clipboard operation
maglev copied to clipboard

Nested collection paths

Open jespr opened this issue 12 years ago • 6 comments

Is it possible to do nested collection paths, let's say

class Event < Maglev::Model
  remote_attributes :id, :name
  has_many :photos
end

class Photo < Maglev::Model
  remote_attributes :id, :event_id, :url
  belongs_to :event

  collection_path "/events/:event_id/photos/:id"
end

jespr avatar Jan 07 '13 20:01 jespr

Hmm I see, yeah there should be a way to do that. Another way it could work is along the lines of

belongs_to :event

collection_path event_path + "/photos/:id"

I'd welcome a PR for either, if you're interested?

as a workaround for now, you can also define a function event_id and it'll be used in the URL:

def event_id
  self.event.id
end

clayallsopp avatar Jan 07 '13 23:01 clayallsopp

I'll take a stab at it and get back to you with a PR :)

jespr avatar Jan 08 '13 06:01 jespr

@clayallsopp so you're saying that added def event_id would make my collection_path and member_path being /events/:event_id/photos and /events/:event_id/photos/:id work? I can't seem to get that working either..

jespr avatar Jan 10 '13 04:01 jespr

I can get it working if i manually pass in the params in the find or find_all methods, but I can't by just defining the method in the model

jespr avatar Jan 10 '13 05:01 jespr

Ahh I see, nevermind, I didn't totally think through the example, sorry!

What should work is this:

class Event < Maglev::Model
  remote_attributes :id, :name

  has_many :photos,
    collection_path: "/events/:id/photos",
    member_path: "/events/:event_id/photos/:id"

  def event_id
    self.id
  end
end

event = Event.new(...)

event.photos.find_all do |photos|
end

event.photos.find(13) do |photo|
end

The facebook example does something similar: https://github.com/clayallsopp/maglev/blob/master/examples/FacebookGraph/app/models/user.rb

clayallsopp avatar Jan 10 '13 23:01 clayallsopp

Never got to continue working on this one. Moved to San Francisco recently, and have been tied up in getting settled. I do plan on implementing nested collection paths, though

And thanks your your reply!

jespr avatar Feb 20 '13 17:02 jespr