原谅我模糊的话题,我目前正在开发一个具有三个模型用户、列表和项目的 Rails 应用程序。用户有很多列表,一个列表可以有很多项目。我目前正在研究一种显示用户拥有的列表数量的方法,并且我需要该列表能够为我提供其中的项目数量。我相信有一种方法可以解析这些数据,而无需在列表模型中创建列项。请原谅我,因为我是 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"
}
]
}