我有两个模型通过第三个模型连接:
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
加上 song_in_playlists
表条目中的 track_number
。
根据 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 文档的说明恰恰相反。
我真的不知道该尝试什么了:(
附言:Ruby 1.9.3、Rails 3.2.13
--- 编辑 --- 好吧,我真的不知道为什么,但我得到这个来产生预期的输出:
format.json { render json: @playlist.as_json(
:include => { :song_in_playlists => {
:include => :song, :only => :track_number } } ) }
但是,当尝试在 :song
和 之间添加
,我又遇到同样的错误了..{ :except => [:dropbox_link, :local_path] }
时,:only
最佳答案
这只是部分关于 rails
:include => song_in_playlists {:only => :track_number}
只是不是有效的 ruby 语法
应该是
:include => {:song_in_playlists => {:only => :track_number}}
每次,键是关联名称(song_in_playlists),值是包含一个或多个键的散列 :only
, :except
or :include
如果你想改变 songs 表中的哪些属性在 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
}
})}
关于ruby-on-rails - 使用多级 :include 时 as_json 中的语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17366397/