开发者

Using default_scope in a model, to filter by the correct instanceID

开发者 https://www.devze.com 2023-01-15 19:31 出处:网络
I have two tables: books (id, name, desc, instance_id) instances (id, domain) A user should ONLY be able to see data that is assigned to their instance_id in records...

I have two tables:

books (id, name, desc, instance_id) instances (id, domain)

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

Any thoughts on that idea? Also how c开发者_开发百科an I write that 2nd to last line for Rails 3? 'AND books.instance_id == current.user.instance_id'

Thanks


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

List of Books created by the user:

current_user.books

Creating a new book:

current_user.books.create(:instance => current_user.instance, ..)

Note:

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}))

OR

user.books.build(params[:book].merge(:instance_id => current_user.instance_id}))
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号