0
原諒我的模糊主題,我目前正在使用三種模型用戶,列表和項目來開發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"
}
]
}
我需要能夠得到每個列表的項目數量真的..我不打擾別名 –
使用這個gem你可以爲列表中的json製作模板,你會把list.items.count – Aleks