我在我的应用程序中使用Rails作为后端。使用respond_with
为show
和Activity
模型返回Workout
操作。
关系:
Activity has_many Workouts
Workout has_many Exercises
... belongs_to ...
WorkOut控制器:
def show
respond_with Workout.find(params[:id])
end
活动控制器:
def show
respond_with Activity.find(params[:id])
end
路线:
exercises GET /exercises(.:format) exercises#index
POST /exercises(.:format) exercises#create
exercise GET /exercises/:id(.:format) exercises#show
activity_workouts GET /activities/:activity_id/workouts(.:format) workouts#index
POST /activities/:activity_id/workouts(.:format) workouts#create
activity_workout GET /activities/:activity_id/workouts/:id(.:format) workouts#show
activities GET /activities(.:format) activities#index
POST /activities(.:format) activities#create
activity GET /activities/:id(.:format) activities#show
在浏览器中,我输入以下内容:
http://localhost:3000/activities/1.json
我得到了这个,其中包括此活动1下的所有Workouts
:
{"id":1,"title":"Climbing","description":"climbing 1","created_at":"2017-03-13T17:48:30.220Z","updated_at":"2017-03-13T17:48:30.220Z","user_id":1,"workouts":[{"id":1,"name":"workout 1","description":"workout2","activity_id":1,"created_at":"2017-03-13T17:59:45.742Z","updated_at":"2017-03-13T17:59:45.742Z"},{"id":2,"name":"workout 2","description":"description 2","activity_id":1,"created_at":"2017-03-13T19:27:57.601Z","updated_at":"2017-03-13T19:27:57.601Z"},{"id":3,"name":"workout 3","description":"description 3","activity_id":1,"created_at":"2017-03-13T20:53:53.191Z","updated_at":"2017-03-13T20:53:53.191Z"},{"id":4,"name":"workout 4","description":"des 4","activity_id":1,"created_at":"2017-03-13T20:55:15.965Z","updated_at":"2017-03-13T20:55:15.965Z"}]}
但是当我输入时:
http://localhost:3000/activities/1/workouts/1.json
我刚接触 中的exercises
{"id":1,"name":"workout 1","description":"workout2","activity_id":1,"created_at":"2017-03-13T17:59:45.742Z","updated_at":"2017-03-13T17:59:45.742Z"}
我不知道这两个动作之间的区别是什么。
解决方案:
在model.rb
下添加 def as_json(options = {})
super(options.merge(include: :exercises))
end
答案 0 :(得分:1)
这是我需要获得每个模型下的所有关联。我想没有它,每个模型都会在没有它的情况下出现。谢谢你的帮助!
def as_json(options = {})
super(options.merge(include: :exercises))
end
答案 1 :(得分:-1)
在第一个中,你只要求一个特定的活动 - Activity
,其身份为1(恰好还有一套全套的`锻炼)。
在第二个动作中,您要求通过id进行一项特定的锻炼。 ID为Workout
的{{1}} - 这是您在json中收到的内容
这正是你要求的......;)