开发者

Rails 3, belongs_to, has one? For 3 models, Users, Instances, Books

开发者 https://www.devze.com 2023-01-15 19:25 出处:网络
I have the following models: Users (id, name, email, instance_id, etc...) Instances (id, domain name) Books (id, name, user_id, instance_id)

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?开发者_JS百科

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

thxs


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.


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

0

精彩评论

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

关注公众号