views:

42

answers:

1

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 can I write that 2nd to last line for Rails 3? 'AND books.instance_id == current.user.instance_id'

Thanks

A: 

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}))
KandadaBoggu
Shoot but now when I create a new book, it's assigning instance_id but not user_id and I need both? Why'd that happen?
AnApprentice
Updated my answer, take a look.
KandadaBoggu
@KandadaBoggu thanks for the reply... But not instance_id is not being set :) and user_id is blank. Looking at the dev log, the INSERT shows the user_id value as NULL
AnApprentice
@KandadaBoggu, just noticed I missed your Creating a new book example, I tried that but it's giving a "wrong number of arguments (2 for 1)" I had: "current_user.books.build(params[:book])" and with your code updated to which error'd: "current_user.books.build(params[:book], :instance => current_user.instance)"
AnApprentice
I see a syntax error in your code. I have updated my answer with the correct code, take a look.
KandadaBoggu
Just tried it an updated all the code, instance_id is still not populating. the log shows NULL
AnApprentice
Just checked the logs, it shows "WARNING: Can't mass-assign protected attributes: instance_id"
AnApprentice
Is the instance_id attribute protected? (i.e. have you used instance_accessible OR instance_protected directive in your model?)
KandadaBoggu