views:

59

answers:

3

I have two models Library and Book. In my Library model, I have an array - book_ids. The primary key of Book model is ID.

How do I create a has_many :books relation in my library model?

This is a legacy database we are using with rails.

Thanks.

A: 

If you want to use has_many you could use the options :counter_sql and :finder_sql using the MySQL LIKE or REGEX syntax. But its probably better to first load the Libary model, then parse the book_ids column and load the books, or directly build a query with that string.

gregor
A: 

Consider using :serialize method with ActiveRecord:

http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M002284

it might do what you want

Tam
+1  A: 

Your database schema doesn't really conform with the prescribed Rails conventions so you will probably have a hard time making the default has_many association work. Have you tried fiddling with the custom SQL options with it thought?

If you can't get the built in has_many association to work, you'll have to roll your own. I would define the books and books= methods on your Library model, and inside them set a virtual attribute, which you then save as an array in the database. Perhaps something like this:

class Book > ActiveRecord::Base; end

class Library > ActiveRecord::Base

  before_save :serialize_books

  def books
    @books || nil
  end

  def books=(new_books)
    @books = new_books
  end

  private
  def serialize_books
    @attributes['books'] = "[" + @books.collect {|b| b.id }.join(',') + "]"
  end
end

That up there wouldn't pull out the dataIf you wanted to go even more gung ho and support single query find operations, you could use some custom SQL in a scope or override find and add it to the default options. Comment if you want help with any of this!

hornairs