使用Sinatra获取与Datamapper相关的记录

时间:2013-04-25 20:42:21

标签: ruby sinatra datamapper

我目前正在开发一个小型后端,管理与相关位置相关的事件。不幸的是,这是我第一次使用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

是否有一种简单的方法可以将位置作为相关事件对象输出中的参数?

非常感谢您的支持!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

@events.to_json(:relationships=>{:location=>{}})