On Wed, Sep 8, 2010 at 12:55 AM, nobosh <[email protected]> wrote: > I'm trying to work out your suggestion on how to not have a > instance_id in books. can you take a look at let me know what's wrong > and if this is what you suggest? thxs! > > 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 Note < ActiveRecord::Base > belongs_to :user > belongs_to :instance > end > > > .... Then to actually get all the notes for instance_id = 1 > > class NotesController < ApplicationController > def index > @books = current_user.instance_books > . > end > . > . > end > > > current_user.instance_books doesn't return the right results. Ideas? > thxs
I don't think has_many :through will work that way - it needs a real join table as far as I know. One with two belongs_to relationships. If you're wanting to keep instance_id on books, your original code can work, but Book belongs_to Instance, not has_one Instance :through User. If you want to ensure the instance is the same as the user's, you can add a validation. > validate :instance_is_same_as_user_instance > def instance_is_same_as_user_instance > unless self.user and self.instance == self.user.instance > errors.add(:instance, "must be the same as the instance on this Book's User") > end > end -- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

