Thursday, 12 September 2013

RAILS4 mysql2 type ENUM database

RAILS4 mysql2 type ENUM database

it is not a question, but an answer for some question asked (and i asked
myself to before) about implementation and use of database Mysql possible
of enum type columns.
I never find any answer about that (wow... some turn around and other
simulation (bad i think) who really never use the enum fonction of
database). But we are on ruby cade... why not do it easy ? why not have
this inside directly ? i don't know, but make it works is not so hard
(prouve that: I consider am a newbie with rails/ruby):
First step: IN MODEL "concerned" FILE (for me it was for tes: "movie.rb"),
insert this in the class
class Movie < ActiveRecord::Base
attr :enum_all
def enum_all(what)
retour = Hash.new
db = Mysql2::Client.new(:host => "localhost",
:username => "root",
:password => "overaquaworks",
:database => "mediatheque_development",
:socket => "/tmp/mysql.sock")
query = "SELECT SUBSTRING(COLUMN_TYPE,5) FROM
information_schema.COLUMNS WHERE
TABLE_SCHEMA=\"mediatheque_development\" AND TABLE_NAME=\"movies\" AND
COLUMN_NAME=\"#{what.to_s}\""
db.query(query).each { |answer| retour.store(nil,
answer["SUBSTRING(COLUMN_TYPE,5)"].scan(/\w+\s*\w+(?=')/) ) }
retour
end
end
Second step: IN CONTROLLER PART FILE "concerned" (for me it was
"movies_controller.rb")
update the part who talk about ":permit" and add enum_all method we just
made here in first step. Like exemple, add like a column inside:
def movie_params
params.require(:movie).permit(:title, :description, :image,
:image_url, :note, :style, :torrent_id, :date, :enum_all)
end
Third step: IN VIEW PART OF "concerned form style" (or other you need for)
(for me it was, for the test: "_form.html.erb")
<div class="field">
<%= f.label :style %><br>
<%= f.select(:style, @movie.enum_all(:style), @movie.enum_all(:style)
) %>
</div>
this create via "select" method a select button from wich you can see that
there is automatically the enum list of concerned possible entries.
I can say that, with this method (easy) you can implement enum type of
column than rails4 don't know to use with ActiveRecord. You can also
define some restriction entries for be sure that nothing can be insert in
place of choice... but what for ? the DB do it back for you.
i hope that ActiveRecord will do it himself easy more by insert the
ability inside his code. I don't know how to do it... so if someone can
said me how to upgrade the ActiveRecord gem file, i will be happy to learn
this and contribute (maybe something already exist and i never find in the
www...). have a good day.

No comments:

Post a Comment