原谅我模糊的话题,我目前正在开发一个有三个模型用户,列表和项目的rails应用程序。用户有许多列表,列表可以有很多项。我目前正在开发一种方法,显示用户拥有的列表数量,我需要列表才能给出其中的项目数。我相信有一种解析这些数据的方法,而不必在列表模型中创建列项。原谅我,因为我是新手,我确信有一个非常简单的方法。下面是我的方法的语法,以及类列表和项目。提前致谢。 (我只是想在列表数据中解析每个列表中的项目数量)
def showLists
pageSize = 10
pageNum = 1
if (params[:limit])
pageSize = (params[:limit])
pageSize = pageSize.to_i
end
pageNum= (params[:page])
pageNum = pageNum.to_i
@key = PrivateKey.find(1)
@key = @key.key
if (params[:apiKey]) == @key
@user = User.find_by_facebookexternalId(params[:id])
if @user.access_key.key == (params[:accessToken])
y =(pageSize*pageNum)
x =(y-pageSize)
@list = @user.lists
total= @list.count
@list = @list.all(:select=>[:name,:id,:listtype,:description ], :include=>[:items=>@list[x].items.count])
@list = @list[x .. y]
#listResponse={:name=>@list.name}
response = {:total =>total,:page => pageNum, :limit=> pageSize, :userId=> @user.id, :accessToken=> @user.access_key.key , :list=>@list }
#response = {:lists => @list}
respond_to do |format|
format.json {render :json => response}
end
end
end
end
架构信息
# == Schema Information
#
# Table name: lists
#
# id :integer not null, primary key
# name :string(255)
# active :boolean
# user_id :integer
# listtype :string(255)
# description :text
# roughlist :boolean
# created_at :datetime not null
# updated_at :datetime not null
#
class List < ActiveRecord::Base
attr_accessible :name, :active , :type , :description , :roughlist, :listtype
belongs_to :user, :foreign_key => :user_id
has_many :map_list_items
has_many :items, :through => :map_list_items
#has_and_belongs_to_many :items
end
And my item schema is here
# == Schema Information
#
# Table name: items
#
# id :integer not null, primary key
# name :string(255)
# description :string(255)
# user_id :integer
# barcode :string(255)
# asin_id :string(255)
# isbn_id :string(255)
# barcode_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class Item < ActiveRecord::Base
belongs_to :barcode , :foreign_key => :barcode_id
has_many :map_item_tags
has_many :map_list_items
has_many :lists, :through => :map_list_items
#has_and_belongs_to_many :lists
end
我得到的json文件样本位于
之下{
"total": 3,
"page": 1,
"limit": 10,
"userId": 5,
"accessToken": "BAAFdQiIeExEBAOwtEtFXgI0c2k9kka3EQbEBDca2FGJZBQyIOLGfnJQr7k1FaGFEx6dzzWxQkxZB4uFSEj3HvZARyZBKLtTzn9NhEXEBtsBxuPBf2O5PxtofkZC4GQg9OmWGahJ42kZBuEay68rlDb",
"list": [
{
"description": "",
"id": 1,
"listtype": "christmas",
"name": "mom"
},
{
"description": "",
"id": 2,
"listtype": "christmas",
"name": "mom"
},
{
"description": "",
"id": 3,
"listtype": "christmas",
"name": "mom"
}
]
}
答案 0 :(得分:0)
对json使用acts_as_api gem。 它使得即使通过模型也能轻松制作json。 在那里,您可以简单地添加自己的归因。