2017-07-17 39 views
0

需要將原始元組保存到數據庫中。將原始元組保存到數據庫中 - elixir

值:

conn.adapter = {Plug.Adapters.Cowboy.Conn, {:http_req, #Port<0.14529>, ranch_tcp, :keepalive, #PID<0.528.0>, "GET", :"HTTP/1.1", {{127, 0, 0, 1}, 2866}, "localhost", :undefined, 4000, "/click", :undefined, "campaign_id=44", undefined, [], [{"host", "localhost:4000"}, {"user-agent", "Mozilla/5.0 X11; Ubuntu; Linux x86_64; rv:54.0) Gecko/20100101 Firefox/54.0"}, "accept", text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"}, {"accept-anguage", "en-US,en;q=0.5"}, {"accept-encoding", "gzip, deflate"}, "cookie", _ga=GA1.1.1071807366.1485427699"}, {"connection", "keep-alive"}, {"upgrade-nsecure-requests", "1"}], [{"connection", ["keep-alive"]}], :undefined, [], waiting, "", :undefined, false, :waiting, [], "", :undefined}} 
enter code here 

嘗試作爲,

field :field5, {:array, :string} 

P1.Repo.insert!(%P1.TestTable{field1: "Header Track",field2: ip, field3: conn.host, field5: conn.adapter}) 

但它拋出的錯誤作爲,

TestTable.field5` in `insert` does not match type {:array, :string} 

或者至少,需要這些數據轉換爲字符串,並保存在db

+1

您能否提供更多信息?喜歡*什麼*不工作? –

+1

你能告訴你爲什麼要這樣做嗎?元組包括端​​口和pid,這些端口和pid在稍後檢索值時可能不存在或不相同。您可以使用'inspect'將其轉換爲字符串,如果您只想稍後查看該值並且不需要返回確切的值。如果你真的想存儲這個確切的值,有':erlang.term_to_binary/1'和':erlang.binary_to_term/1'來序列化/反序列化任意項。 – Dogbert

+0

@zv肯定,更新 –

回答

1

該元組不是一個字符串數組。如果你只是想以後能夠看到的元組的內容,並且不需要使用這些值的實際元組,你可以使用inspect/1的元組轉換爲字符串表示,並將其保存爲一個字符串:

# Schema 
field :field5, :string 

# Controller 
Repo.insert(%TestTable{..., field5: inspect(conn.adapter)}) 

如果您以後確實需要元組作爲元組,則可以使用:erlang.term_to_binary/1進行序列化,並使用:erlang.binary_to_term/1進行反序列化。 (請務必閱讀binary_to_term文檔中的警告部分。)

# Schema 
field :field5, :binary 

# Controller 
Repo.insert(%TestTable{..., field5: :erlang.term_to_binary(conn.adapter)}) 

# Later 
test = Repo.get(TestTable, 123) 
adapter = :erlang.binary_to_term(test.field5, [:safe])