Passing Array of Objects from Js to Rails

passing array of objects from js to rails

You should use JSON.stringify in Javascript, which takes either an array or hash as its argument (since these are the only valid JSON constructions). It returns a form which is the Javascript object serialized to JSON.

On the Ruby side, you'll receive a JSON encoded string, so you'll need to require 'json' (this is done automatically in Rails) and use JSON.parse(string). This will give you a Ruby object.

Pass array of objects from JS to rails controller for creation

Try this

$.ajax({
url: '/categories',
type: 'POST',
dataType: 'json',
data: { categories: gameCategories},
success: function (response) {
console.log(response);
}
});
def category_params
params.permit(categories: [:name, :bgg_id])
end

Rails 3 passing a rails array to javascript function which uses a javascript array

Going to JSON as suggested a couple times in this post always gave me something like this.

[{"mile":{"date":"2011-05-20","mpg":"18.565887006952"}},{"mile":{"date":"2011-06-01","mpg":"18.471164309032"}}]

What I really wanted was just this... [[2011-05-20, 18.56][2011-06-01, 18.47]]

So I handled it with a helper like so.

  def chart_values()
@chart_values = '['
@mpg_values.each do |m|
@chart_values = @chart_values+'['+m.date.to_s+', '+m.mpg.round(2).to_s+'],'
end
@chart_values = @chart_values+']'
end

Then passed chart_values() to the javascript.

Likely not the best solution but it gave me the desired values in the format I needed.

How to pass array data to controller for storing data in the Pg database in rails, so that i can add multiple records at the same time in rails?

Mukesh, welcome to Stack Overflow!

Here is what you can do. Change the params of type ActionController::Parameters to a hash before initializing the Section. Maybe like this:

@section = Section.new(params[:section].to_h) #=> params[:section].to_h is a hash

More on this here:
https://api.rubyonrails.org/classes/ActionController/Parameters.html#method-i-to_hash

Also, I would create all the objects and then save them in the db to avoid any corrupted data. If you use Rails 6, you could use the insert_all method and pass an array of hashes. Like:

Section.insert_all(
[
section1,
section2,
...
]
)

If you use Rails 5, you can use create with multiple hashes, like:

Section.create!((
[
section1,
section2,
...
]
)

Keep also in mind that it is good practice to use transactions to avoid corruption.

Using JavaScript to submit an array and a file object to a Rails backend

I figured out that I can do this using ActiveStorage's Direct Upload feature.

In my JavaScript:

// Import DirectUpload from ActiveStorage somewhere above here.
onChange(file) {
this.uploadFile(file);
},
uploadFile(file) {
const url = "/rails/active_storage/direct_uploads";
const upload = new DirectUpload(file, url);

upload.create((error, blob) => {
if (error) {
// TODO: Handle this error.
console.log(error);
} else {
this.game.coverBlob = blob.signed_id;
}
})
},
onSubmit() {
let genre_ids = Array.from(this.game.genres, genre => genre.id);
let engine_ids = Array.from(this.game.engines, engine => engine.id);
let submittableData = { game: {
name: this.game.name,
genre_ids: genre_ids,
engine_ids: engine_ids
}};

if (this.game.coverBlob) {
submittableData['game']['cover'] = this.game.coverBlob;
}

fetch(this.submitPath, {
method: this.create ? 'POST' : 'PUT',
body: JSON.stringify(submittableData),
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': Rails.csrfToken()
},
credentials: 'same-origin'
})
}

I then figured out that, with the way DirectUpload works, I can just send the coverBlob variable to the Rails application, so it'll just be a string. Super easy.

Ruby on Rails: send javascript array of arrays to ruby controller

JSON.parse is your friend:

ar = JSON.parse(params[:total_changes])
#=> [[4, 2, "", "15"], [4, 3, "", "12"], [4, 4, "", "14"]]

Most likely you'll need to update your AJAX call to something like:

$.ajax({
type: "POST",
url: "/qtl_table/save",
data: { total_changes: JSON.stringify(totalChanges) },
success: function() { alert("Success!"); }
});

to give your array parameter total_changes name.

Wrong format when passing an array of strings to java script from Rails controller

Remove the extra quotation marks:

var verbatims = <%= raw @verbatims.to_json %>;


Related Topics



Leave a reply



Submit