在模型中使用 default_scope,通过正确的 instanceID 进行过滤 [英] Using default_scope in a model, to filter by the correct instanceID
问题描述
我有两张桌子:
书籍(id、name、desc、instance_id)实例(id,域)
books (id, name, desc, instance_id) instances (id, domain)
用户应该只能看到记录中分配给他们的 instance_id 的数据...
A user should ONLY be able to see data that is assigned to their instance_id in records...
对于书籍、模型,为了实现这一点,我正在考虑使用默认范围.. 类似:
For the books, model, to accomplish this, I'm thinking about using a default scope.. Something like:
class Books < ActiveRecord::Base
attr_accessible :name, :description
belongs_to :user
default_scope :order => 'books.created_at DESC'
AND books.instance_id == current.user.instance_id
end
对这个想法有什么想法吗?另外,如何为 Rails 3 编写倒数第二行?'AND books.instance_id == current.user.instance_id'
Any thoughts on that idea? Also how can I write that 2nd to last line for Rails 3? 'AND books.instance_id == current.user.instance_id'
谢谢
推荐答案
在模型中访问当前用户不是一个好主意.我将按如下方式实现:
It's not a good idea to access the current user inside the model. I would implement this as follows:
class Instance < ActiveRecord::Base
has_many :users
has_many :books
end
class User < ActiveRecord::Base
belongs_to :instance
has_many :books, :order => "created_at DESC"
has_many :instance_books, :through => :instance, :source => :books,
:order => "created_at DESC"
end
class Book < ActiveRecord::Base
belongs_to :user
belongs_to :instance
end
与用户实例关联的书籍列表:
List of Books associated with the user instance:
current_user.instance_books
用户创建的图书列表:
current_user.books
创建新书:
current_user.books.create(:instance => current_user.instance, ..)
注意:
您的图书创建语法错误.build
方法以散列作为参数.您传递的是两个参数而不是一个.
Your book creation syntax is wrong. The build
method takes hash as parameter. You are passing two arguments instead of one.
user.books.build(params[:book].merge(:instance => current_user.instance}))
或
user.books.build(params[:book].merge(:instance_id => current_user.instance_id}))
这篇关于在模型中使用 default_scope,通过正确的 instanceID 进行过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!