Ruby on Rails 3 (3.1) ActiveModel Associations (tableless nested models)
Asked Answered
N

3

8

How to impliment ActiveModel associations (tableless nested models)?

For example:

book has many chapters

With ActiveRecord I would create two models and assosiate them with has_many and belongs_to. But ActiveModel doesn't have such functionality. How can I implement this?

Ninette answered 6/7, 2011 at 8:18 Comment(0)
C
5

You simply can't do it that way. It is not active record.

You can check ActiveModel documentation (and source code) at :

https://github.com/rails/rails/tree/master/activemodel

I guess you have to do it old fashion way, using an array of chapters and a reference to the book in the chapters.

Hope this helps!

Cryptogram answered 6/7, 2011 at 8:59 Comment(2)
Thank you for your response, Dominic. I'm new to Ruby language, can you explain what you mean by saying "a reference to the book in the chapters"?Ninette
Happy I helped! So : Your "chapter" class should have a "book" member which you would affect to the actual "book" that the "chapter" is in. In the "book" class, add an array of all the "chapters" that the book contains.Cryptogram
C
7

With rails versions >= 2.3.x you can use the activerecord-tableless gem. With that gem you can have associations and validations without a database.

Update

I have been added as author to the gem and I have updated the gem to support newer Rails versions. So now we can have tableless models with associations in Rails versions >= 2.3

Cheliform answered 5/8, 2011 at 10:7 Comment(1)
@Tilo you probably already figured out but... You can use ActiveModel::Model api.rubyonrails.org/classes/ActiveModel/Model.htmlLeastwise
C
5

You simply can't do it that way. It is not active record.

You can check ActiveModel documentation (and source code) at :

https://github.com/rails/rails/tree/master/activemodel

I guess you have to do it old fashion way, using an array of chapters and a reference to the book in the chapters.

Hope this helps!

Cryptogram answered 6/7, 2011 at 8:59 Comment(2)
Thank you for your response, Dominic. I'm new to Ruby language, can you explain what you mean by saying "a reference to the book in the chapters"?Ninette
Happy I helped! So : Your "chapter" class should have a "book" member which you would affect to the actual "book" that the "chapter" is in. In the "book" class, add an array of all the "chapters" that the book contains.Cryptogram
E
0

You can check out this answer for another way to do it.

class Tableless < ActiveRecord::Base
    def self.columns() @columns ||= []; end

    def self.column(name, sql_type = nil, default = nil, null = true)
        columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type.to_s, null)
    end 

    attr_accessor :id, :name, :value

    has_many :stuff_things
    has_many :things, :through => :stuff_things

end
Eliathan answered 5/8, 2015 at 14:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.