views:

237

answers:

2

I have the following models: Users (id, name, email, instance_id, etc...) Instances (id, domain name) Books (id, name, user_id, instance_id)

In Rails 3, When a new book is created, I need the user_id, and instance_id to be populated based on the current_user.

Currently, user_id is being assigned when I create a new book but not instance_id? What needs to happen in rails to make that field get filled out on book creation?

Also, shouldn't rails be error'ing given that I can create books without that instance_id filled out?

thxs

+1  A: 

Rails will only produce an error in this case if (a) you have a validation that's failing, or (b) you have database foreign keys that aren't being satisfied.

What's an instance? i.e. if instance_id is to be populated based on the current user, what attribute of the user should supply it? (the instance_id? why?)

mylescarrick
Just saw your other question at http://stackoverflow.com/questions/3663861/using-default-scope-in-a-model-to-filter-by-the-correct-instanceid.Is instance a join model? i.e. you have a many-to-many relationship between users and books?If so... the convention is to call it something like user_books - i.e. to _mean_ something - to describe what it is.
mylescarrick
Instances are companies (like yammer). Users belong to instances. and when you create a book I need to record the instance_id and the user_id. InstanceID because a company should only see their records, user_id so I know who owns the note. Does that help?
AnApprentice
+1  A: 

It looks like you have de-normalized User and Book models by adding reference to Instance model. You can avoid the redundant reference unless you have a specific reason.

I would rewrite your models as follows:

class Instance  < ActiveRecord::Base
  has_many :users
  has_many :books, :through => :users, :order => "created_at DESC"
end

class User < ActiveRecord::Base
  belongs_to :instance
  has_many   :books, :order => "created_at DESC"
end


class Book < ActiveRecord::Base
  belongs_to :user
  has_one    :instance, :through => :user
end

Now to create a new book for a user.

current_user.books.build(...)

To get a list of the books belonging to user's instance:

current_user.instance.books

To get a list of the books created by the user:

current_user.books

Make sure you index the instance_id column in users table and user_id column in books table.

KandadaBoggu
@KandadaBoggu I just tried your idea here. and instance_id is not being populated. In the dev log it's NULL
AnApprentice
In the book controller, here is the command I'm using to create the record "@book = current_user.books.build(params[:book])" It's inserting NULL for instance_ID user_id is working fine.
AnApprentice