我有两个模型通过第三个模型连接:
Playlist has_many :song_in_playlists, :dependent => :destroy
has_many :songs, :through => :song_in_playlists
Song has_many :song_in_playlists, :dependent => :destroy
has_many :playlists, :through => :song_in_playlists
该song_in_playlist
表仅列出了playlist_id
、song_id
和track_number
。
调用时/playlists/1.json
,我想获取一个包含播放列表属性的 json 散列,其中包含另一个散列,其中包含歌曲(如/songs.json
加上track_number
来自song_in_playlists
表条目的)。
根据Rails API,我应该能够通过以下方式实现这一点:
def show
@playlist = Playlist.find(params[:id])
[...]
respond_to do |format|
format.html # show.html.erb
format.json { render json: @playlist.as_json(
:include => { :song_in_playlists => {
:only => :track_number, :include => :songs {
:except => [:dropbox_link, :local_path] } } }
) }
end
end
end
但是,我得到的是以下内容:
/home/sloth/audiomixer/app/controllers/playlists_controller.rb:30: syntax error, unexpected '{', expecting '}'
:only => :track_number, :include => :songs {
^
/home/sloth/audiomixer/app/controllers/playlists_controller.rb:31: syntax error, unexpected '}', expecting keyword_end
:except => [:dropbox_link, :local_path] } } }
^
/home/sloth/audiomixer/app/controllers/playlists_controller.rb:103: syntax error, unexpected $end, expecting keyword_end
所以我尝试减少复杂性,调用
format.json { render json: @playlist.as_json(
:include => song_in_playlists {
:only => :track_number } ) }
但我遇到了类似的错误。一旦我在括号之间加上任何大括号,Rails 就会抱怨,尽管 API 文档说明了相反的情况。
我真的不知道该尝试什么了:(
PS:Ruby 1.9.3,Rails 3.2.13
--- 编辑 --- 好的,我真的不知道为什么,但我得到了这个来产生预期的输出:
format.json { render json: @playlist.as_json(
:include => { :song_in_playlists => {
:include => :song, :only => :track_number } } ) }
但是,当尝试在and{ :except => [:dropbox_link, :local_path] }
之间添加时,我再次遇到相同的错误..:song
, :only