How to add an element into an array of a Serialize Field using Ruby on RailsHow can I “pretty” format my JSON output in Ruby on Rails?Preferred method to store PHP arrays (json_encode vs serialize)A concise explanation of nil v. empty v. blank in Ruby on RailsHow can I rename a database column in a Ruby on Rails migration?How do I get the current absolute URL in Ruby on Rails?Ruby on Rails Server optionsGson: How to exclude specific fields from Serialization without annotationsReference - What does this error mean in PHP?Add unique ids to serialized objectsRepresenting null in JSON
Does a large simulator bay have standard public address announcements?
Contradiction proof for inequality of P and NP?
How do I reattach a shelf to the wall when it ripped out of the wall?
How can Republicans who favour free markets, consistently express anger when they don't like the outcome of that choice?
Pulling the rope with one hand is as heavy as with two hands?
I preordered a game on my Xbox while on the home screen of my friend's account. Which of us owns the game?
Partitioning the Reals into two Locally Uncountable, Dense Sets
Was Dennis Ritchie being too modest in this quote about C and Pascal?
Alignment of various blocks in tikz
Does Gita support doctrine of eternal samsara?
How do I check if a string is entirely made of the same substring?
Is it idiomatic to construct against `this`
Implications of cigar-shaped bodies having rings?
Minor Revision with suggestion of an alternative proof by reviewer
Which big number is bigger?
What is the philosophical significance of speech acts/implicature?
How to write a column outside the braces in a matrix?
What is the most expensive material in the world that could be used to create Pun-Pun's lute?
Size of electromagnet needed to replicate Earth's magnetic field
Providing evidence of Consent of Parents for Marriage by minor in England in early 1800s?
How does a program know if stdout is connected to a terminal or a pipe?
Can SQL Server create collisions in system generated constraint names?
Is Diceware more secure than a long passphrase?
How to denote matrix elements succinctly?
How to add an element into an array of a Serialize Field using Ruby on Rails
How can I “pretty” format my JSON output in Ruby on Rails?Preferred method to store PHP arrays (json_encode vs serialize)A concise explanation of nil v. empty v. blank in Ruby on RailsHow can I rename a database column in a Ruby on Rails migration?How do I get the current absolute URL in Ruby on Rails?Ruby on Rails Server optionsGson: How to exclude specific fields from Serialization without annotationsReference - What does this error mean in PHP?Add unique ids to serialized objectsRepresenting null in JSON
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
I have a field call query_data
defined as text
in my MySQL database.
In my model I defined this field as serialize :query_data, JSON
.
The JSON format I would like to save and retrieve look like that:
:items => [
:id => 1,
:id => 2,
:id => 3
]
I have a collection (in that case, called items
) that contain an array of objects.
I was wondering, what's the best way to add or delete an Item.
Ex: remove :id => 2
from my items list and add `:id => 4 to it
mysql ruby-on-rails json serialization
add a comment |
I have a field call query_data
defined as text
in my MySQL database.
In my model I defined this field as serialize :query_data, JSON
.
The JSON format I would like to save and retrieve look like that:
:items => [
:id => 1,
:id => 2,
:id => 3
]
I have a collection (in that case, called items
) that contain an array of objects.
I was wondering, what's the best way to add or delete an Item.
Ex: remove :id => 2
from my items list and add `:id => 4 to it
mysql ruby-on-rails json serialization
add a comment |
I have a field call query_data
defined as text
in my MySQL database.
In my model I defined this field as serialize :query_data, JSON
.
The JSON format I would like to save and retrieve look like that:
:items => [
:id => 1,
:id => 2,
:id => 3
]
I have a collection (in that case, called items
) that contain an array of objects.
I was wondering, what's the best way to add or delete an Item.
Ex: remove :id => 2
from my items list and add `:id => 4 to it
mysql ruby-on-rails json serialization
I have a field call query_data
defined as text
in my MySQL database.
In my model I defined this field as serialize :query_data, JSON
.
The JSON format I would like to save and retrieve look like that:
:items => [
:id => 1,
:id => 2,
:id => 3
]
I have a collection (in that case, called items
) that contain an array of objects.
I was wondering, what's the best way to add or delete an Item.
Ex: remove :id => 2
from my items list and add `:id => 4 to it
mysql ruby-on-rails json serialization
mysql ruby-on-rails json serialization
asked Mar 22 at 17:40
JudgeProphetJudgeProphet
1,04321932
1,04321932
add a comment |
add a comment |
3 Answers
3
active
oldest
votes
Ruby on Rails has some nice methods to move seamlessly between JSON and Ruby.
thing = :items => [
:id => 1,
:id => 2,
:id => 3
]
thing.to_json # ""items":["id":1,"id":2,"id":3]"
thing.to_json
is essentially what's happening in the serializer. If you want them back to Ruby, you can just do:
@items = @thing.query_data
JSON.parse(@items) # "items"=>["id"=>1, "id"=>2, "id"=>3]}
Now that we can easily move between the two, lets just use Ruby syntax to deal with adding and deleting keys.
thing = :items => [
:id => 1,
:id => 2,
:id => 3
]
thing[:items] = thing[:items].append(:id => 4) # adding a new item
thing[:items] = thing[:items].select # removing an item
add a comment |
First: The second argument to serialize should be the class of object you're storing in the field. You should have serialize :query_data, Hash
instead.
Besides that, there aren't really any established best practices for working with serialized data. It really just depends too much on the structure of your data. You might as well ask, "what's the best way to add or delete an item from a hash?"
But since this is a hash you should make sure to keep dirty attributes in mind. If you were to do something like:
items = my_model.query_data[:items]
items.reject! item
items += id: 4
then the model wouldn't know that query_data changed and should be updated on save.
my_model.changed?
# => false
my_model.save
# Won't actually save changes to db.
To avoid this, you can:
A) Make sure you only ever set my_model.query_data directly
B) Explicitly call my_model.query_data_will_change!
after changing that field so that it will be properly updated on save.
add a comment |
Base on @veridian-dynamics (thanks for your help!) Here what I did.
Model:
class MyModel < ApplicationRecord
serialize :item_data, JSON
end
Controller:
class ItemController < ApplicationController
before_action :authenticate_user!
def add_item
begin
mymodel = MyModel.find_or_create_by(id: param[:model_id])
if mymodel .item_data.blank?
item = :items => []
else
item = mymodel.item_data.deep_symbolize_keys
end
bookmark_exist = item[:items].any? i
if !bookmark_exist
item[:items] = item[:items ].append(id: params[:id]) # adding a new item
end
mymodel.item_data = item
mymodel.save
return render :json => item, :status=> 200
rescue Exception => e
return render :json =>:errors=>e.message, :status=> 400
puts "ERROR: #e.message"
end
end
def delete_item
begin
mymodel = MyModel.find_by(id: params[:model_id])
if mymodel.present? && mymodel.item_data.present?
item = mymodel.item_data.deep_symbolize_keys
item[:items] = (item[:items].select itm) # remove an item
mymodel.item_data = item
mymodel.save
return render :json => item, :status=> 200
end
rescue Exception => e
return render :json =>:errors=>e.message, :status=> 400
puts "ERROR: #e.message"
end
end
end
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55305116%2fhow-to-add-an-element-into-an-array-of-a-serialize-field-using-ruby-on-rails%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
Ruby on Rails has some nice methods to move seamlessly between JSON and Ruby.
thing = :items => [
:id => 1,
:id => 2,
:id => 3
]
thing.to_json # ""items":["id":1,"id":2,"id":3]"
thing.to_json
is essentially what's happening in the serializer. If you want them back to Ruby, you can just do:
@items = @thing.query_data
JSON.parse(@items) # "items"=>["id"=>1, "id"=>2, "id"=>3]}
Now that we can easily move between the two, lets just use Ruby syntax to deal with adding and deleting keys.
thing = :items => [
:id => 1,
:id => 2,
:id => 3
]
thing[:items] = thing[:items].append(:id => 4) # adding a new item
thing[:items] = thing[:items].select # removing an item
add a comment |
Ruby on Rails has some nice methods to move seamlessly between JSON and Ruby.
thing = :items => [
:id => 1,
:id => 2,
:id => 3
]
thing.to_json # ""items":["id":1,"id":2,"id":3]"
thing.to_json
is essentially what's happening in the serializer. If you want them back to Ruby, you can just do:
@items = @thing.query_data
JSON.parse(@items) # "items"=>["id"=>1, "id"=>2, "id"=>3]}
Now that we can easily move between the two, lets just use Ruby syntax to deal with adding and deleting keys.
thing = :items => [
:id => 1,
:id => 2,
:id => 3
]
thing[:items] = thing[:items].append(:id => 4) # adding a new item
thing[:items] = thing[:items].select # removing an item
add a comment |
Ruby on Rails has some nice methods to move seamlessly between JSON and Ruby.
thing = :items => [
:id => 1,
:id => 2,
:id => 3
]
thing.to_json # ""items":["id":1,"id":2,"id":3]"
thing.to_json
is essentially what's happening in the serializer. If you want them back to Ruby, you can just do:
@items = @thing.query_data
JSON.parse(@items) # "items"=>["id"=>1, "id"=>2, "id"=>3]}
Now that we can easily move between the two, lets just use Ruby syntax to deal with adding and deleting keys.
thing = :items => [
:id => 1,
:id => 2,
:id => 3
]
thing[:items] = thing[:items].append(:id => 4) # adding a new item
thing[:items] = thing[:items].select # removing an item
Ruby on Rails has some nice methods to move seamlessly between JSON and Ruby.
thing = :items => [
:id => 1,
:id => 2,
:id => 3
]
thing.to_json # ""items":["id":1,"id":2,"id":3]"
thing.to_json
is essentially what's happening in the serializer. If you want them back to Ruby, you can just do:
@items = @thing.query_data
JSON.parse(@items) # "items"=>["id"=>1, "id"=>2, "id"=>3]}
Now that we can easily move between the two, lets just use Ruby syntax to deal with adding and deleting keys.
thing = :items => [
:id => 1,
:id => 2,
:id => 3
]
thing[:items] = thing[:items].append(:id => 4) # adding a new item
thing[:items] = thing[:items].select # removing an item
edited Mar 22 at 18:05
answered Mar 22 at 18:00
Veridian DynamicsVeridian Dynamics
945313
945313
add a comment |
add a comment |
First: The second argument to serialize should be the class of object you're storing in the field. You should have serialize :query_data, Hash
instead.
Besides that, there aren't really any established best practices for working with serialized data. It really just depends too much on the structure of your data. You might as well ask, "what's the best way to add or delete an item from a hash?"
But since this is a hash you should make sure to keep dirty attributes in mind. If you were to do something like:
items = my_model.query_data[:items]
items.reject! item
items += id: 4
then the model wouldn't know that query_data changed and should be updated on save.
my_model.changed?
# => false
my_model.save
# Won't actually save changes to db.
To avoid this, you can:
A) Make sure you only ever set my_model.query_data directly
B) Explicitly call my_model.query_data_will_change!
after changing that field so that it will be properly updated on save.
add a comment |
First: The second argument to serialize should be the class of object you're storing in the field. You should have serialize :query_data, Hash
instead.
Besides that, there aren't really any established best practices for working with serialized data. It really just depends too much on the structure of your data. You might as well ask, "what's the best way to add or delete an item from a hash?"
But since this is a hash you should make sure to keep dirty attributes in mind. If you were to do something like:
items = my_model.query_data[:items]
items.reject! item
items += id: 4
then the model wouldn't know that query_data changed and should be updated on save.
my_model.changed?
# => false
my_model.save
# Won't actually save changes to db.
To avoid this, you can:
A) Make sure you only ever set my_model.query_data directly
B) Explicitly call my_model.query_data_will_change!
after changing that field so that it will be properly updated on save.
add a comment |
First: The second argument to serialize should be the class of object you're storing in the field. You should have serialize :query_data, Hash
instead.
Besides that, there aren't really any established best practices for working with serialized data. It really just depends too much on the structure of your data. You might as well ask, "what's the best way to add or delete an item from a hash?"
But since this is a hash you should make sure to keep dirty attributes in mind. If you were to do something like:
items = my_model.query_data[:items]
items.reject! item
items += id: 4
then the model wouldn't know that query_data changed and should be updated on save.
my_model.changed?
# => false
my_model.save
# Won't actually save changes to db.
To avoid this, you can:
A) Make sure you only ever set my_model.query_data directly
B) Explicitly call my_model.query_data_will_change!
after changing that field so that it will be properly updated on save.
First: The second argument to serialize should be the class of object you're storing in the field. You should have serialize :query_data, Hash
instead.
Besides that, there aren't really any established best practices for working with serialized data. It really just depends too much on the structure of your data. You might as well ask, "what's the best way to add or delete an item from a hash?"
But since this is a hash you should make sure to keep dirty attributes in mind. If you were to do something like:
items = my_model.query_data[:items]
items.reject! item
items += id: 4
then the model wouldn't know that query_data changed and should be updated on save.
my_model.changed?
# => false
my_model.save
# Won't actually save changes to db.
To avoid this, you can:
A) Make sure you only ever set my_model.query_data directly
B) Explicitly call my_model.query_data_will_change!
after changing that field so that it will be properly updated on save.
answered Mar 22 at 18:36
GlyokoGlyoko
906515
906515
add a comment |
add a comment |
Base on @veridian-dynamics (thanks for your help!) Here what I did.
Model:
class MyModel < ApplicationRecord
serialize :item_data, JSON
end
Controller:
class ItemController < ApplicationController
before_action :authenticate_user!
def add_item
begin
mymodel = MyModel.find_or_create_by(id: param[:model_id])
if mymodel .item_data.blank?
item = :items => []
else
item = mymodel.item_data.deep_symbolize_keys
end
bookmark_exist = item[:items].any? i
if !bookmark_exist
item[:items] = item[:items ].append(id: params[:id]) # adding a new item
end
mymodel.item_data = item
mymodel.save
return render :json => item, :status=> 200
rescue Exception => e
return render :json =>:errors=>e.message, :status=> 400
puts "ERROR: #e.message"
end
end
def delete_item
begin
mymodel = MyModel.find_by(id: params[:model_id])
if mymodel.present? && mymodel.item_data.present?
item = mymodel.item_data.deep_symbolize_keys
item[:items] = (item[:items].select itm) # remove an item
mymodel.item_data = item
mymodel.save
return render :json => item, :status=> 200
end
rescue Exception => e
return render :json =>:errors=>e.message, :status=> 400
puts "ERROR: #e.message"
end
end
end
add a comment |
Base on @veridian-dynamics (thanks for your help!) Here what I did.
Model:
class MyModel < ApplicationRecord
serialize :item_data, JSON
end
Controller:
class ItemController < ApplicationController
before_action :authenticate_user!
def add_item
begin
mymodel = MyModel.find_or_create_by(id: param[:model_id])
if mymodel .item_data.blank?
item = :items => []
else
item = mymodel.item_data.deep_symbolize_keys
end
bookmark_exist = item[:items].any? i
if !bookmark_exist
item[:items] = item[:items ].append(id: params[:id]) # adding a new item
end
mymodel.item_data = item
mymodel.save
return render :json => item, :status=> 200
rescue Exception => e
return render :json =>:errors=>e.message, :status=> 400
puts "ERROR: #e.message"
end
end
def delete_item
begin
mymodel = MyModel.find_by(id: params[:model_id])
if mymodel.present? && mymodel.item_data.present?
item = mymodel.item_data.deep_symbolize_keys
item[:items] = (item[:items].select itm) # remove an item
mymodel.item_data = item
mymodel.save
return render :json => item, :status=> 200
end
rescue Exception => e
return render :json =>:errors=>e.message, :status=> 400
puts "ERROR: #e.message"
end
end
end
add a comment |
Base on @veridian-dynamics (thanks for your help!) Here what I did.
Model:
class MyModel < ApplicationRecord
serialize :item_data, JSON
end
Controller:
class ItemController < ApplicationController
before_action :authenticate_user!
def add_item
begin
mymodel = MyModel.find_or_create_by(id: param[:model_id])
if mymodel .item_data.blank?
item = :items => []
else
item = mymodel.item_data.deep_symbolize_keys
end
bookmark_exist = item[:items].any? i
if !bookmark_exist
item[:items] = item[:items ].append(id: params[:id]) # adding a new item
end
mymodel.item_data = item
mymodel.save
return render :json => item, :status=> 200
rescue Exception => e
return render :json =>:errors=>e.message, :status=> 400
puts "ERROR: #e.message"
end
end
def delete_item
begin
mymodel = MyModel.find_by(id: params[:model_id])
if mymodel.present? && mymodel.item_data.present?
item = mymodel.item_data.deep_symbolize_keys
item[:items] = (item[:items].select itm) # remove an item
mymodel.item_data = item
mymodel.save
return render :json => item, :status=> 200
end
rescue Exception => e
return render :json =>:errors=>e.message, :status=> 400
puts "ERROR: #e.message"
end
end
end
Base on @veridian-dynamics (thanks for your help!) Here what I did.
Model:
class MyModel < ApplicationRecord
serialize :item_data, JSON
end
Controller:
class ItemController < ApplicationController
before_action :authenticate_user!
def add_item
begin
mymodel = MyModel.find_or_create_by(id: param[:model_id])
if mymodel .item_data.blank?
item = :items => []
else
item = mymodel.item_data.deep_symbolize_keys
end
bookmark_exist = item[:items].any? i
if !bookmark_exist
item[:items] = item[:items ].append(id: params[:id]) # adding a new item
end
mymodel.item_data = item
mymodel.save
return render :json => item, :status=> 200
rescue Exception => e
return render :json =>:errors=>e.message, :status=> 400
puts "ERROR: #e.message"
end
end
def delete_item
begin
mymodel = MyModel.find_by(id: params[:model_id])
if mymodel.present? && mymodel.item_data.present?
item = mymodel.item_data.deep_symbolize_keys
item[:items] = (item[:items].select itm) # remove an item
mymodel.item_data = item
mymodel.save
return render :json => item, :status=> 200
end
rescue Exception => e
return render :json =>:errors=>e.message, :status=> 400
puts "ERROR: #e.message"
end
end
end
answered Mar 26 at 12:09
JudgeProphetJudgeProphet
1,04321932
1,04321932
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55305116%2fhow-to-add-an-element-into-an-array-of-a-serialize-field-using-ruby-on-rails%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown