1

I am creating a ruby on rails application which stores a users favourite publications and have stumbled across a problem and need some help.

The user is able to add as many different types of publications as they choose, such as books, movies, newspapers, articles etc. Each of those publication types has different attributes for example books may have an author and publisher, and a movie may have a director and producer. There are many attributes to a single publication.

My app currently looks like this: I have a publications resource which stores types of publications. There is a resource called attribs which stores all the attributes for a specific publication. And finally there there is a third resource called favourites.

class Publication < ActiveRecord::Base
 has_many :attribs

 # columns in this model => name, hidden

 # example ( :name => "movie", :hidden => false )
end

class Attrib < ActiveRecord::Base
 belongs_to :publication

 # columns in this model => publication_id, name, datatype

 # example (:publication_id => 1, :name => "Movie Title", :datatype => "string")
 # example (:publication_id => 1, :name => "Director", :datatype => "string")
end

class Favourite < ActiveRecord::Base

 # columns in this model => data, reason

 # example (:data => "[serialized form data]", :reason => "some reason why its a fav")

end

When a user creates a new favourite and selects a publication, I would like a form to be generated with the attributes the user chose for that specific publication.

Is there a way I can dynamically create a model/form with attributes that are stored in a database table?

As Formtastic is a dynamic form generator, can this be used to create the form?

To me this seems overly complicated, but I can't figure another way to do it without having an awfully large amount of tables in my application.

Nick
  • 239
  • 3
  • 14

2 Answers2

1

Formtastic and Simple Form gems need a model to be present to generate the forms for you. Check out this post here. Create a Tableless Model. Then create a Temporary Model using the tableless model. Then fetch the columns for Temporary Model from a table holding the column values for that model, like it is done for Foo in that link. Using an instance of the Temporary Class you can use Formtastic and generate form for it.

Community
  • 1
  • 1
0

I think you can implement it by yourself.

@publication.attribs.each do |attrib|
  case attrib.datatype
  when "string"
    f.text_field attrib.name
  when "text"
    f.text_area attrib.name
  when "password"
    f.password_field attrib.name
  ...
end
fl00r
  • 82,987
  • 33
  • 217
  • 237