我有两张桌子:
create_table "friendships", :force => true do |t|
t.integer "user1_id"
t.integer "user2_id"
t.boolean "hasaccepted"
t.datetime "created_at"
t.datetime "updated_at"
end
和
create_table "users", :force => true do |t|
t.string "email"
t.string "password"
t.string "phone"
t.boolean "gender"
t.datetime "created_at"
t.datetime "updated_at"
t.string "firstname"
t.string "lastname"
t.date "birthday"
end
我需要向用户显示Friendrequests
的列表,因此我在我的控制器中使用此方法:
def getfriendrequests
respond_to do |format|
case params[:id]
when "to_me"
@friendrequests = Friendship.find(:all, :conditions => { :user2_id => session[:user], :hasaccepted => false })
when "from_me"
@friendrequests = Friendship.find(:all, :conditions => { :user1_id => session[:user], :hasaccepted => false })
end
format.xml { render :xml => @friendrequests }
format.json { render :json => @friendrequests }
end
end
我使用AJAX做几乎所有事情,所以要使用UID user2_id
获取用户的名字和姓氏(to_me
param稍后出现,现在不要担心),我需要一个for循环,它进行多个AJAX调用。这很糟糕并且需要花费很多带宽。所以我更喜欢getfriendrequests
也返回相应用户的名字和姓氏,例如, JSON响应不会是:
[
{
"friendship": {
"created_at": "2010-02-19T13:51:31Z",
"user1_id": 2,
"updated_at": "2010-02-19T13:51:31Z",
"hasaccepted": false,
"id": 11,
"user2_id": 3
}
},
{
"friendship": {
"created_at": "2010-02-19T16:31:23Z",
"user1_id": 2,
"updated_at": "2010-02-19T16:31:23Z",
"hasaccepted": false,
"id": 12,
"user2_id": 4
}
}
]
而是:
[
{
"friendship": {
"created_at": "2010-02-19T13:51:31Z",
"user1_id": 2,
"updated_at": "2010-02-19T13:51:31Z",
"hasaccepted": false,
"id": 11,
"user2_id": 3,
"firstname": "Jon",
"lastname": "Skeet"
}
},
{
"friendship": {
"created_at": "2010-02-19T16:31:23Z",
"user1_id": 2,
"updated_at": "2010-02-19T16:31:23Z",
"hasaccepted": false,
"id": 12,
"user2_id": 4,
"firstname": "Mark",
"lastname": "Gravell"
}
}
]
我想到了getfriendrequests
方法中的for循环,但我不知道如何实现它,也许有一种更简单的方法。它也必须适用于XML。谁能帮我?感谢
答案 0 :(得分:0)
致电时
render :xml => @friendrequests
Rails迭代数组中的每个元素并调用ActiveRecord::Base#to_xml
方法。
同样,:json
选项表示调用ActiveRecord::Base#to_json
。
to_xml和to_json都有一个:methods
选项,其中包含要包含在序列化中的方法数组。
解决方案非常简单。覆盖这些方法。
class Friendship
# ...
def firstname
# here get the first name
end
def lastname
# here get the last name
end
def to_xml(options = {})
options[:methods] ||= [:firstname, :lastname]
super(options)
end
def to_json(options = {})
options[:methods] ||= [:firstname, :lastname]
super(options)
end
end