How to create/maintain ID field in Sequel Pro via Ruby and mysql2

眉间皱痕 提交于 2019-12-12 05:29:07

问题


In Sequel Pro, created a table using this statement:

CREATE TABLE dogs(
id INT PRIMARY KEY AUTO_INCREMENT,
name TEXT,
color TEXT
);

Since the id value is being created by MySQL, I would like to set/create/maintain the id field in ruby so that puts dog.id will not be an empty string.

Was wondering if this piece of code would accomplish that:

def new_from_hash(hash)
    Dog.new(hash["name"], hash["color"]).tap {|dog| dog.id = hash["id"]}
end

NOTE: I am not running rails; just plain ruby, the gem mysql2, and Sequel Pro.

Thank you!


回答1:


Okay, I believe I finally figured this out.

"Since the id value is being created by MySQL, I would like to set/create/maintain the id field in ruby so that puts dog.id will not be an empty string."

=> because id value is automatically assigned in MySQL Ruby has no way of knowing what that id value is and therefore calling dog.id will return an empty string.

=> I need to find a way to map an objects' id value in ruby such that it is the same as the id automatically assigned to the object when I insert it in MySQL database.

=> Pay attention to the statement used to create Table dogs:

CREATE TABLE dogs(
id INT PRIMARY KEY AUTO_INCREMENT,
name TEXT,
color TEXT
);

it translates to each dog create has an id (which is automatically assigned to it), a name, and a color. There are two approaches to thinking of the storage of a dog objects' information:

dog = { "id" => 'some integer', "name" => "simba", "color" => "grey" }

dog = [1, "simba", "grey"]

I typically like to use arrays to store information but this time around I used a hash (because when I call .inspect on dog (not Dog) the result is something like this:

#<Dog:0x007fbf74c55068 @name="samba", @color="grey">

which makes me think of a hash data structure:

{ "id"=> 1, "name"=>"simba", "color"=>"grey"}

In Ruby, I do this:

def row_hash(hash)
  hash={}
  Dog.new(hash[name], hash[color]).tap { |id| id = hash[id] }
end

Where hash_row refers to the row that holds each dog object's attribute. This basically lets Ruby know that each time it instantiates a new instance of the class Dog it should tap into that instantiation and map hash[id] to "id".

Doing this allows me to access the value of "id" in ruby.

PS: This just occurred to me. I probably will edit this answer after it percolates for a while.



来源:https://stackoverflow.com/questions/20670481/how-to-create-maintain-id-field-in-sequel-pro-via-ruby-and-mysql2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!