简体   繁体   中英

How to exclude fields of has_many associations when rendering xml

Part 1.

I have a Series which has_many :articles . In my show action, if xml is requested, I'd like to include all the associated :articles , but I really only want three of the fields: :title , :date , and :id

How can I do this?

Part 2.

Instead of doing this from the controller, I wonder if it would be better just to override to_xml in my model. Is this good practice? How would I do this?

Thanks so much!

Edit

Sector was almost right, but it needs to be a hash:

render :xml => @series.to_xml(:include => { :articles => { :only => [:title, :date, :id] } })

Part 1

respond_to do |format|
  format.xml {
    render :xml => @series.to_xml(:include => { :articles => { :only => [:title, :date, :id] } })
  }
end

Part 2

Controller is good place for this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM