This repository has been archived by the owner on Jan 2, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 52
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
7 changed files
with
245 additions
and
209 deletions.
There are no files selected for viewing
33 changes: 20 additions & 13 deletions
33
book-content/es/5-interacting-with-the-database-sequel/1-setting-up.markdown
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Original file line | Diff line number | Diff line change |
---|---|---|---|
@@ -1,26 +1,33 @@ | |||
# Instalacion y configuracion | # Instalación y configuración | ||
|
|
||
## Generando un proyecto utilizando Sequel | ## Generando un proyecto utilizando Sequel | ||
A fin de crear una aplicacion Merb utilizando Sequel, | A fin de crear una aplicación Merb utilizando Sequel, | ||
To create a core app with Sequel, merb-gen takes a `--orm` flag. | usted debe agregar la opción ``--orm`` | ||
cuando ejecute el comando ``merb-gen``. | |||
|
|
||
$ merb-gen core --orm sequel new_app | $ merb-gen core --orm sequel nueva_aplicacion | ||
{:lang=shell html_use_syntax=true} | |||
|
|
||
This will build the desired application, but falls a little short when it comes to bells and whistles. | Este comando construirá el esqueleto de la aplicación. | ||
|
|
||
To achieve results similar to merb-gen app, the merb-sequel-stack gem can be used. | A fin de lograr resultados similares a los descriptos anteriormente, | ||
usted puede utilizar la gema ``merb-sequel-stack``. | |||
|
|
||
$ git clone git://github.com/jackdempsey/merb-sequel-stack.git | $ git clone git://github.com/jackdempsey/merb-sequel-stack.git | ||
$ cd merb-sequel-stack/ | $ cd merb-sequel-stack/ | ||
$ rake install | $ rake install | ||
{:lang=shell html_use_syntax=true} | |||
|
|
||
merb-gen will now include a sequel-app generator. | El comando ``merb-gen`` ahora incluirá el generador ``sequel-app``. | ||
This will generate an app that uses Sequel, rspec, and the rest of what can be expected from `merb-gen app`. | Este generara una aplicación que utilice Sequel, RSpec y las demás | ||
funcionalidades que se esperan del comando ``merb-gen app``. | |||
|
|
||
$merb-gen sequel-app new_app | $merb-gen sequel-app nueva_aplicación | ||
{:lang=shell html_use_syntax=true} | |||
|
|
||
By default, `merb-gen sequel-app` will generate a database.yml file that uses sqlite3. | Por defecto, el comando ``merb-gen sequel-app`` generará | ||
For more info, check out the [repository][]. | el archivo ``.config/database.yml`` que utilizará el adaptador SQLite3. | ||
|
|
||
Para mas información, por favor referirse a la página del [stack Sequel Merb][]. | |||
|
|
||
[repository]: http://github.com/jackdempsey/merb-sequel-stack/tree | [stack Sequel Merb]: http://github.com/jackdempsey/merb-sequel-stack/tree |
62 changes: 33 additions & 29 deletions
62
...ontent/es/5-interacting-with-the-database-sequel/2-database-migrations.markdown
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Original file line | Diff line number | Diff line change |
---|---|---|---|
@@ -1,53 +1,57 @@ | |||
#Database Migrations | # Migraciones hacia la base de datos | ||
Las migraciones en Sequel serán generadas por | |||
cualquier tarea del comando ``merb-gen`` que cree un modelo. | |||
|
|
||
Sequel migrations will be generated with any merb-gen task that creates a model. | $ merb-gen model articulo | ||
|
|||
$ merb-gen model post | |||
Generating with model generator: | Generating with model generator: | ||
[ADDED] spec/models/post_spec.rb | [ADDED] spec/models/articulo_spec.rb | ||
[ADDED] app/models/post.rb | [ADDED] app/models/articulo.rb | ||
[ADDED] schema/migrations/001_post_migration.rb | [ADDED] schema/migrations/001_articulo_migration.rb | ||
$ cat schema/migrations/001_articulo_migration.rb | |||
$ cat schema/migrations/001_post_migration.rb | {:lang=shell html_use_syntax=true} | ||
|
|
||
# For details on Sequel migrations see | class ArticuloMigration < Sequel::Migration | ||
# http://sequel.rubyforge.org/ | |||
|
|||
class PostMigration < Sequel::Migration | |||
|
|||
def up | def up | ||
create_table :posts do | create_table :articulos do | ||
primary_key :id | primary_key :id | ||
end | end | ||
end | end | ||
|
|
||
def down | def down | ||
drop_table :posts | drop_table :articulos | ||
end | end | ||
|
|||
end | end | ||
{:lang=ruby html_use_syntax=true} | |||
|
|
||
Columns can be added to the table definition using the `#column` method or the column type can be used as the method in the specification. | Usted puede agregar columnas a la definición de una tabla determinada | ||
|
utilizando el método ``#column`` o también puede definir el tipo de columna | ||
class PostMigration < Sequel::Migration | como un método en la especificación de la tabla en cuestión. | ||
|
|
||
class ArticuloMigration < Sequel::Migration | |||
def up | def up | ||
create_table :posts do | create_table :articulos do | ||
primary_key :id | primary_key :id | ||
string :title | string :titulo | ||
text :body | text :cuerpo | ||
boolean :published, :default => false | boolean :publicado, :default => false | ||
end | end | ||
end | end | ||
def down | def down | ||
drop_table :posts | drop_table :articulos | ||
end | end | ||
|
|||
end | end | ||
|
{:lang=ruby html_use_syntax=true} | ||
After editing the migration, it can be run with a rake task. |
|
||
Luego de haber modificado la migración, | |||
usted debe ejecutar el siguiente comando. | |||
|
|
||
$ rake sequel:db:migrate | $ rake sequel:db:migrate | ||
{:lang=shell html_use_syntax=true} | |||
|
|||
Una bandera de versión de la migración puede ser especificada | |||
con el fin de volver a una determinada versión de migración. | |||
|
|||
Para mas información, por favor referirse a la página del [proyecto Sequel][]. | |||
|
|
||
A VERSION flag can be specified to roll back to particular migration versions. | [proyecto Sequel]: http://sequel.rubyforge.org/ |
116 changes: 67 additions & 49 deletions
116
...interacting-with-the-database-sequel/3-data-retrieval-and-manipulation.markdown
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Original file line | Diff line number | Diff line change |
---|---|---|---|
@@ -1,65 +1,83 @@ | |||
#Database Retreival and Manipulation | # Obtención y manipulación de datos | ||
|
## Encontrando entradas en la base de datos | ||
##Finding records | El uso de corchetes permitirá la obtención de un solo objeto. | ||
|
Una llave primaria debe ser utilizada como parámetro | ||
Square brackets will return a single object. | o también una colección, la cual es utilizada como un conjunto de condiciones. | ||
A primary key can be passed in as parameter, or a hash, which is used as a set of conditions. | |||
|
|
||
$ merb -i | $ merb -i | ||
>> Post[1] | >> Artículo[1] | ||
=> #<Post @values={:published=>false, :body=>"This is a blog post", :id=>1, :title=>"First Post"}> | => #<Artículo @values={:publicado => false, | ||
:cuerpo => "Esto es un artículo no publicado.", | |||
:id => 1, :titulo => "Primer artículo"}> | |||
>> Artículo[:titulo => 'Primer artículo'] | |||
=> #<Artículo @values={:publicado => false, | |||
:cuerpo => "Esto es un artículo no publicado.", | |||
:id => 1, :titulo => "Primer artículo"}> | |||
{:lang=shell html_use_syntax=true} | |||
|
|
||
>> Post[:title => 'First Post'] | La instrucción ``Articulo.all`` retornará un conjunto de objetos ``Articulo``, | ||
=> #<Post @values={:published=>false, :body=>"This is a blog post", :id=>1, :title=>"First Post"}> | los cuales corresponderán a todas las entradas existentes en la respectiva tabla. | ||
|
|||
`Post.all` will return the entire set of Post objects. | |||
The Sequel model is treated like a Sequel dataset. | |||
All of the selection and refinement methods available to a dataset can be applied to a Sequel::Model. | |||
To simplify the following examples, the SQL statements produced by Sequel::Model have been shown. | |||
|
|
||
$ merb -i | El modelo utilizado en Sequel es tratado como un conjunto de datos de Sequel. | ||
>> Post.all | Todos los métodos de selección y refinamiento disponibles en el conjunto de datos Sequel | ||
~ SELECT * FROM `posts` | pueden ser utilizados con el modelo Sequel. | ||
A fin de simplificar los siguientes ejemplos, | |||
>> Post.filter(:published => true).all | se mostrara el código de las consultas SQL generado por ``Sequel::Model``. | ||
~ SELECT * FROM `posts` WHERE (`published` = 't') | |||
|
|
||
>> Post.exclude(:published => true).all | $ merb -i | ||
~ SELECT * FROM `posts` WHERE (`published` != 't') | >> Artículo.all | ||
~ SELECT * FROM `artículos` | |||
>> Post.order(:created_at.desc).paginate(2, 10).all | >> Artículo.filter(:publicado => true).all | ||
~ SELECT * FROM `posts` ORDER BY `created_at` DESC LIMIT 10 OFFSET 10 | ~ SELECT * FROM `artículos` WHERE (`publicado` = 't') | ||
>> Artículo.exclude(:publicado => true).all | |||
~ SELECT * FROM `artículos` WHERE (`publicado` != 't') | |||
>> Artículo.order(:created_at.desc).paginate(2, 10).all | |||
~ SELECT * FROM `artículos` ORDER BY `created_at` DESC LIMIT 10 OFFSET 10 | |||
{:lang=shell html_use_syntax=true} | |||
|
|
||
##The Other Three Letters in CRUD | ## Creando entradas en la base de datos | ||
|
|||
###Create | |||
|
|
||
>> p = Post.create(:title => 'second post', :body => 'another post for something') | >> artículo = Artículo.create(:titulo => 'Segundo artículo', | ||
=> #<Post @values={:published=>false, :body=>"another post for something", :id=>2, :title=>"second post"}> | :cuerpo => 'Otro artículo para algo.') | ||
>> p.new? | => #<Artículo @values={:publicado => false, | ||
:cuerpo => "Otro artículo para algo.", | |||
:id => 2, :titulo => "Segundo artículo"}> | |||
>> artículo.new? | |||
=> false | => false | ||
{:lang=shell html_use_syntax=true} | |||
|
|
||
###Update | ## Actualizando entradas en la base de datos | ||
|
|
||
>> p = Post[2] | >> artículo = Artículo[2] | ||
=> #<Post @values={:published=>false, :body=>"another post for something", :id=>2, :title=>"second post"}> | => #<Artículo @values={:publicado => false, | ||
>> p.update(:title => 'replacement title') | :cuerpo => "Otro artículo para algo.", | ||
=> #<Post @values={:published=>false, :body=>"another post for something", :id=>2, :title=>"replacement title"}> | :id => 2, :titulo => "Segundo artículo"}> | ||
>> articulo.update(:titulo => 'Titulo reemplazado') | |||
=> #<Articulo @values={:publicado => false, | |||
:cuerpo => "Otro artículo para algo.", | |||
:id => 2, :titulo => "Título reemplazado"}> | |||
{:lang=shell html_use_syntax=true} | |||
|
|
||
###Delete | ## Destruyendo entradas en la base de datos | ||
|
|
||
>> p = Post[2] | >> artículo = Articulo[2] | ||
=> p.destroy | => artículo.destroy | ||
>> p.exists? | >> artículo.exists? | ||
=> false | => false | ||
{:lang=shell html_use_syntax=true} | |||
|
|
||
Mass deletions are also available. | La destrucción en masa de las entradas también esta disponible. | ||
|
|
||
# This will run destruction hooks on each object | # Este método destruirá toda la información relacionada con el objeto | ||
Post.filter(:user_id => 3).destroy | >>Artículo.filter(:user_id => 3).destroy | ||
|
|
||
# This is faster, but will not run hooks. | # Este método es mas rápido, porque solamente destruirá la información | ||
# It just runs a single query. | # del objeto existente en una sola tabla mediante la ejecución de una | ||
Post.filter(:user_id => 3).delete | # sola consulta hacia la base de datos. | ||
|
>>Artículo.filter(:user_id => 3).delete | ||
A simple way to see Sequel CRUD in action is to merb-gen a resource and view the generated controller. | {:lang=shell html_use_syntax=true} | ||
|
|||
La manera mas simple de observar las | |||
acciones mencionadas anteriormente en acción | |||
es mediante la generación de un recurso y | |||
de observar el código generado en dicho control. |
49 changes: 25 additions & 24 deletions
49
...content/es/5-interacting-with-the-database-sequel/4-model-associations.markdown
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Original file line | Diff line number | Diff line change |
---|---|---|---|
@@ -1,40 +1,41 @@ | |||
#Model Associations | # Asociaciones entre modelos | ||
La clase ``Sequel::Model`` tiene un conjunto simple de métodos de asociación. | |||
Sequel provee los siguientes métodos para crear asociaciones en la base de datos: | |||
|
|||
* ``one-to-one`` (uno-a-uno) | |||
* ``many-to-one`` (muchos-a-uno) | |||
* ``one-to-many`` (uno-a-muchos) | |||
* ``many-to-many`` (muchos-a-muchos) | |||
|
|
||
`Sequel::Model` has a very simple set of association methods. | A continuación se detallara cada uno de los métodos mencionados. | ||
Sequel provides `many_to_one`, `one_to_many` and `many_to_many` to create database associations. | |||
|
|
||
## Uno a Uno | |||
|
|
||
##One to Many | class Usuario < Sequel::Model | ||
|
one_to_many :direcciones, :one_to_one => true | ||
class Post < Sequel::Model | |||
one_to_many :comments | |||
end | end | ||
{:lang=ruby html_use_syntax=true} | {:lang=ruby html_use_syntax=true} | ||
|
|
||
## Uno a Muchos | |||
|
|
||
|
class Artículo < Sequel::Model | ||
The Post class above now has a set of association methods similar to ActiveRecord's has\_many. | one_to_many :comentarios | ||
end | |||
{:lang=ruby html_use_syntax=true} | |||
|
|||
La clase ``Artículo`` ahora tiene un conjunto de métodos de asociación | |||
similar al método ``has\_many`` proporcionado por ActiveRecord. | |||
|
|
||
##Many to One | ## Muchos a uno | ||
|
|
||
class Post < Sequel::Model | class Artículo < Sequel::Model | ||
many_to_one :user | many_to_one :usuario | ||
end | end | ||
{:lang=ruby html_use_syntax=true} | {:lang=ruby html_use_syntax=true} | ||
|
|
||
##Many to Many | ## Muchos a Muchos | ||
|
|
||
class Post < Sequel::Model | class Artículo < Sequel::Model | ||
many_to_many :tags | many_to_many :tags | ||
end | end | ||
{:lang=ruby html_use_syntax=true} | {:lang=ruby html_use_syntax=true} | ||
|
|||
## One to One | |||
|
|||
class User < Sequel::Model | |||
one_to_many :addresses, :one_to_one => true | |||
end | |||
{:lang=ruby html_use_syntax=true} | |||
|
|||
|
|||
|
Oops, something went wrong.