0

我目前正在开发一个小型后端,管理具有相关位置的事件。不幸的是,这是我第一次使用 Ruby/Sinatra/Datamapper。经过 3 小时试图找到解决方案,我必须写这篇文章。

我定义了两个资源:

class Event
  include DataMapper::Resource  
  property :id,                  Integer, :key => true 
  property :name,                 Text 
  property :description,          Text 

  has 1, :location
end


class Location
  include DataMapper::Resource 

  property :id,                  Integer, :key => true 
  property :name,                 Text 
  property :latitude,             Float
  property :longitude,            Float    

  belongs_to :event 
end 

这是我列出所有事件的路线:

get "/events/" do  
  @events = Event.all

  content_type :json
  @events.to_json
end

有没有一种简单的方法可以在关联事件对象的输出中将位置作为参数获取?

非常感谢您的支持!

4

2 回答 2

1
require 'rubygems'
require 'sinatra'
require 'dm-core'
require 'dm-migrations'
require 'dm-sweatshop' # for fixtures
require 'json'

DataMapper::Logger.new($stdout, :debug)
DataMapper.setup(:default, 'sqlite::memory:')

class Event
  include DataMapper::Resource
  property :id, Serial # will automatically become an auto-increment key
  property :name, String # defaults to being max 50 char length
  property :description, Text, :lazy => false # defaults to true
  belongs_to :location # instead of one-to-one relation, which are rarely useful
end

class Location
  include DataMapper::Resource
  property :id, Serial
  property :name, String
  property :latitude, Float # perhaps decimal with less precision would suffice
  property :longitude, Float
  has n, :events
end

DataMapper.finalize.auto_migrate!

# Define some fixtures to have some data to play around with
def rand_float(min, max); rand * (max - min) + min end

Location.fix {{
  :name => /\w+/.gen,
  :latitude => rand_float(40.0, 43.0),
  :longitude => rand_float(4.8, 5.4)
}}

Event.fix {{
  :name => /\w+/.gen,
  :description => /[:sentence:]/.gen[5..100],
  :location => Location.pick
}}

100.of { Location.gen; Event.gen }

# Search events by properties of its association
get "/events/:location_name" do |location_name|
  @events = Event.all(Event.location.name => location_name)
  @events.to_json
end

# Return both objects in the same array
get "/events/" do
  @events = Event.map {|e| [e, e.location] }
  @events.to_json
end
于 2013-04-26T08:53:28.790 回答
0

当我深入了解 to_json 选项时,我终于自己找到了答案

@events.to_json(:relationships=>{:location=>{}})
于 2013-04-26T08:09:31.483 回答