Hi,
you could try using scopes like:
class Books < ActiveRecord::Base
# .... code ....
scope :personal, proc {|user| where(:instance_id => user.instance_id) }
# .... code ...
end
Now you can do:
@personal_books = Books.personal(@user)
you can read more about scopes here: http://www.railsdispatch.com/posts/rails-3-makes-life-better (scroll down a little bit)
Another way is to make an association like
User has_many Books through Instance
Then you'd have an additional legacy table mapping user to books over their instance.
It's an n:m relation. So a book could belong to multiple instances.
It would look like this:
User Table:
Users (name, email, password, instance_id, etc...)
Book Table:
Books (name, desc) # no more instance_id !
Mapping Table:
Assignments (instance_id, book_id)
And your Models would look like:
class Assignment < ActiveRecord::Base
belongs_to :book # foreign key - book_id
belongs_to :instance # foreign key - instance_id
end
class Instance < ActiveRecord::Base
has_many :assignments
has_many :books, :through => :assignments
end
class Books < ActiveRecord::Base
has_many :assignments
has_many :users, :through => :assignments
end
class User < ActiveRecord::Base
belongs_to :instance
end
The code to get all books of an user's instance would look like:
@user = User.find(:first)
@books = @user.instance.books.find(:all)
(I recommend you to read http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html )
Edit
You could try this if a book always belongs to only one instance:
class User < ActiveRecord::Base
belongs_to :instance
end
class Instance < ActiveRecord::Base
has_many :users
has_many :books
end
class Books < ActiveRecord::Base
belongs_to :instance
end
So you grab a user's books like:
@user.instance.books.find(:all)