我正在使用此代码
@events = Event.all(:include => [:facility_infos, :activity_infos], :conditions => ['infos.language_id = ? AND activity_infos_events.language_id = ?', 1, 1], :order => :time)
respond_to do |format|
format.xml { render :xml => @events.to_xml(
:skip_types => true,
:except => :created_at,
:include => {
:facility_infos => {:only => :title},
:activity_infos => {:only => :title}
})
}
获取以下XML
<events>
<event>
<activity-id>23</activity-id>
<everyday>false</everyday>
<facility-id>10</facility-id>
<home>true</home>
<id>3</id>
<time>2011-04-21T17:30:00Z</time>
<updated-at>2011-04-21T17:31:23Z</updated-at>
<facility-infos>
<facility-info>
<title>Campi da calcetto</title>
</facility-info>
</facility-infos>
<activity-infos>
<activity-info>
<title>Torneo di calcetto</title>
</activity-info>
</activity-infos>
</event>
</events>
我希望看起来像这样:
<events>
<event>
<activity-id>23</activity-id>
<everyday>false</everyday>
<facility-id>10</facility-id>
<home>true</home>
<id>3</id>
<time>2011-04-21T17:30:00Z</time>
<updated-at>2011-04-21T17:31:23Z</updated-at>
<facility>Campi da calcetto</facility>
<activity>Torneo di calcetto</activity>
</event>
</events>
请告诉我如何更改我的代码才能获得该代码?
谢谢!
修改
我在事件模型中的关系:
belongs_to :activity
belongs_to :facility
has_many :activity_infos, :through => :activity, :source => :infos, :class_name => "Info"
has_many :facility_infos, :through => :facility, :source => :infos, :class_name => "Info"
def infos
activity_infos + facility_infos
end
答案 0 :(得分:1)
刚刚编辑过。
的确,如果您的关系是has_many
,则以下内容没有意义:
<facility>Campi da calcetto</facility>
<activity>Torneo di calcetto</activity>
因为您要显示许多facility_infos
和activity_infos
。记住这句话我建议如下。
在模型中覆盖to_xml
,如下所示:
def to_xml options={}
super(options) do |xml|
xml.facility_infos do
facility_infos.each do |facility|
xml.facility_info facility.title
end
end
xml.activity_infos do
activity_infos.each do |activity|
xml.activity_info activity.title
end
end
end
end
简单地以这种方式检索你的期望:
@events.to_xml(
:skip_types => true,
:except => :created_at,
)