我的一个项目的模型设置如下(使用Rails 3.2和Mongoid 3.0):
class Parent
include Mongoid::Document
has_many :kids
def schools
return kids.map { |kid| kid.school }
end
end
class School
include Mongoid::Document
has_many :kids
end
class Kid
include Mongoid::Document
belongs_to :parent
belongs_to :school
end我的父模型充当我用Devise设置的标准用户模型。我想要一个具有index和show方法的SchoolController,它只允许访问家长有孩子的学校。根据这个网站:http://www.therailsway.com/2007/3/26/association-proxies-are-your-friend/,最好的方法是这样做:
def index
@schools = current_user.schools
end
def show
@school = current_user.schools.find(params[:id])
end然而,因为Mongoid不允许has_many :through关系,所以Parent#schools是一个自定义方法,它返回一个数组,而不是一个关联代理,因此#find不是一个可以使用的方法。有没有办法从一组文档中创建一个关联代理?或者,有没有更聪明的方法来处理这个简单的访问控制问题?
发布于 2012-09-27 03:40:28
我给返回的数组一个#find方法:
class Parent
include Mongoid::Document
has_many :kids
def schools
schools = self.kids.map { |kid| kid.school }
# Returns a school with the given id. If the school is not found,
# raises Mongoid::Errors::DocumentNotFound which mimics Criteria#find.
def schools.find(id)
self.each do |school|
return school if school.id.to_s == id.to_s
end
raise Mongoid::Errors::DocumentNotFound.new(School, {:_id => id})
end
return schools
end
end这样我就可以让我的控制器逻辑保持简单和一致:
class ParentsController < ApplicationController
def show
@school = current_user.schools.find(params[:id])
end
end不确定在这一点上是否有更好的方法。
https://stackoverflow.com/questions/12603493
复制相似问题