我有两个通过第三个连接的模型:
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
表条目。)
根据the 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 } } ) }
但是,当我尝试在{ :except => [:dropbox_link, :local_path] }
和:song
之间添加, :only
时,我再次遇到相同的错误..
答案 0 :(得分:3)
这只是部分关于rails
:include => song_in_playlists {:only => :track_number}
只是无效的ruby语法
这应该是
:include => {:song_in_playlists => {:only => :track_number}}
每次键都是关联名称(song_in_playlists),值是包含一个或多个键:only
,:except
或:include
如果你想更改json中歌曲表中的属性,那么你需要
format.json { render json: @playlist.as_json(
:include => { :song_in_playlists => {
:include => :song, :only => :track_number } } ) }
并将:song
替换为描述您要对歌曲做什么的哈希,例如
format.json { render json: @playlist.as_json(
:include => {
:song_in_playlists => {
:include => {
:song => {
:except => [:dropbox_link, :local_path]
}
},
:only => :track_number
}
})}