问题
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