Rails 4: Create JSON array in array inside input - ruby-on-rails

For now, i have this inside my form:
<%= f.input :document, collection: #documents, wrapper: false, label: false, input_html: {class: 'fleft mleft5'} %>
which will production in json array:
[{
"document":"126"
}]
My Controller under create method:
document: params[:ng_geofence][:document]
My Model
def as_hash(format=:google)
{
document: document
}
end
%w[document].each do |key|
define_method(key) do
value && JSON.parse(value)[key]
end
end
my question is how to get the output for something like this:
[{
"document":
{
"id":"126"
}
}]
---- UPDATED ----
If i changed my form to:
<%= select_tag "ng_geofence[driver_notification][document][id]", options_from_collection_for_select(#documents, "id", "name"), include_blank: true %>
I get this error: 757: unexpected token at '{"document"=>{"id"=>"126"}}'
Probably because of "=>" instead of ":"

Solved my own problem. Here what i did:
My Controller under create method:
document: {
id: params[:ng_geofence][:document]
}
My Model
def as_hash(format=:google)
{
document: { id: document }
}

Related

Rails/Stimulus: What is the best way to get form field values when handling form submission with Stimulus?

I have a form but Stimulus will handle its submission.
<%= form_with model: #booking, data: { controller: 'booking', action: 'booking#submitForm:prevent' } do |form| %>
<%= form.text_field :name, data: { 'booking-target' => 'name' } %>
<%= form.text_field :pet_name, data: { 'booking-target' => 'pet' } %>
<%= form.submit "Submit form" %>
<% end %>
import { Controller } from "#hotwired/stimulus"
export default class extends Controller {
static targets = ['name', 'pet']
submitForm() {
console.log('Submitting form')
console.log('Name: ' + this.nameTarget.value)
console.log('Pet: ' + this.petTarget.value)
}
}
The above code works but I have specified the target name for each field in the form. This isn't a problem with a small form but would be cumbersome if the form had many more fields. Is there a more elegant way to expose the field data?
You don't have to specify targets and just use the form directly:
submitForm(e) {
// get it directly from the form
console.log(e.target.name, e.target.name.value)
// or like this
console.log(e.target["pet_name"], e.target["pet_name"].value)
// get everything
const data = Object.fromEntries(new FormData(e.target).entries())
console.log(data)
}
BTW, you can also do this:
# <%= form.text_field :name, data: { 'booking-target' => 'name' } %>
<%= form.text_field :name, data: { booking_target: :name } %>

Rails-7 : Prevent form clear on get request

My problem seems simple.
<%= form_with(url: projects_path, method: :get, data: { turbo_frame: "projects", turbo_action: "advance", controller: "search-form" }) do |form| %>
<%= form.text_field :title, data: { action: "input->search-form#search" } %>
<%= form.collection_select :category, Project.categories.keys, :to_s, :titlecase, { include_blank: true, default: 0 }, data: { action: "change->search-form#search" } %>
<%= form.submit "Search" %>
<% end %>
I've got this form that clears after submitting the get request. I need it to be Get because I'm using Turbo. Is there a way to prevent that via stimulus or simple Rails/Ruby ?
Here is my stimulus file if needed :
import { Controller } from "#hotwired/stimulus"
// Connects to data-controller="search-form"
export default class extends Controller {
search() {
clearTimeout(this.timeout);
this.timeout = setTimeout(() => {
this.element.requestSubmit();
}, 150)
}
}
Preventing the form to empty on an asynchronous request is good but surely when I submit every key stroke. xD
Thanks for the help !

Rails 4 : Saving value as JSON string object/array in PostgreSQL

I have 1 column called 'message_notification' inside table 'configuration'. I want to produce save result as JSON object in this column:
message_notification: [
{
"alert" : "how are you doing today?"
},
{
"alert" : "where have you been today?"
}
]
for the form, i use
<%= simple_form_for(#configuration) do |f| %>
Alert 1: <%= check_box_tag "configuration[message_notification][][alert]", 'how are you doing today?' %><label>Alert 1</label><br/>
Alert 2: <%= check_box_tag "configuration[message_notification][][alert]", 'where have you been today?' %><label>Alert 2</label><br/>
<%= f.submit %>
<% end %>
How to achieve this?
[UPDATED]
above code will resolve as a ruby hash (not as JSON)
my controller
#configuration.message_notification = {
alert: params[:message][:alert]
}.to_json
result:
message_notification: [
{
"alert" => "how are you doing today?"
},
{
"alert" => "where have you been today?"
}
]
[UPDATED 2]
In console:
=> a = value.message_notification
=> "[{\"alert\"=>\"alert1\"}, {\"alert\"=>\"alert2\"}]"
=> puts a
=> [{"alert"=>"alert1"}, {"alert"=>"alert2"}]
=> nil
You can use, to_json to convert the ruby hash to JSON object
just require 'json' in your controller.
params = {"utf8"=>"✓", "_method"=>"new", "authenticity_token"=>"txroAHF2+YZOrm48DtBZdVqKzxLYyHFq4+GWQFnM6kNldXgRZJMPv0yfj‌​0/tfZVpuVvh39UVX4Fb66FNkkCZqA==", "message"=>{"name"=>"Dan Murphy Roundabout Test", "company"=>"transtech", "location_id"=>"", "message_notification"=>[{"alert"=>"alert1"}, {"alert"=>"alert2"}], "commit"=>"save", "controller"=>"message", "action"=>"create", "id"=>"1717"}}
Since your params object is above, according to your requirement you can use,
params['message']['message_notification'] = (params['message']['message_notification'].to_json)
this converts the message_notification in the params to a json object, and stores in the DB.
Here's what I did.
def resource_params
params.require(:appointment_modules_dataset_intake).permit(
:appointment_id,
:main_issue,
:cvf
).tap do |p|
p[:cvf] = JSON.parse(p[:cvf]) # This is the significant line
end
end

Multiple selected data doesn't appear

I use select2 for multiple select. My problem is, I can select multiple value from json data and I can save this data in related model columns. But when I want to update this model, the selected data doesn't appear.
some part of my json data:
{
- categories:[
- {
id:7,
name:"Eğitim Bilimleri Enstitüsü"
},
- {
id: 8,
name: "Eğitim Yönetim Teftişi ve Planlaması 1. Yarıyıl"
},
...
]
}
I have a Moodle class(it is not inheritance from ActiveRecord, just a class and it has some functions which return json data). I am wondering whether it is right approach.
in the content of my form:
<%= simple_form_for(#period) do |f| %>
...
<%= f.input :moodle_connect_ids, collection: Moodle.categories.map {|p| [ p['name'], p['id'] ] }, input_html: {multiple: true} %>
...
<% end %>
I explicitly set moodle_connect_ids to be an array in my controller:
params.require(:period).permit(..., :moodle_connect_ids => [])
in the content of my .js file:
$("#period_moodle_connect_ids").select2({
placeholder: "Moodle Dönem Bağlantılarını Seçiniz",
multiple: true,
allowClear: true
});
When I select to multiple values and save my model, the column's value looks like this:
> Period.last
=> #<Period:0x007fcf53a4d830
id: 25,
...
moodle_connect_ids: "[\"\", \"85\", \"120\"]"
...
Am I on the wrong way? Have you any suggestion?
I've figured out how to do this issue.
I've added selected option in the f.input:
selected: #period.moodle_connect_ids? ? JSON.parse(#period.moodle_connect_ids).map(&:to_i) : []
the input's last state:
<%= f.input :moodle_connect_ids, collection: Moodle.categories.map {|p| [ p['name'], p['id'] ] }, input_html: {multiple: true}, selected: #period.moodle_connect_ids? ? #period.moodle_connect_ids.map(&:to_i) : [] %>

Can't specify a class with simple_form gem with a block

I have the following form but for some reason, I can't get the HTML class to come appear in the resulting code. The documentation suggests this should work, but they don't have an example that uses a block. I've tried a few different things but I haven't found the right answer yet. I have to use a block to get the custom data to appear with the select.
= simple_form_for([:admin, #theme]) do |f|
= f.input :title_bar
= f.input :apple_touch_icon_image, input_html: { class: 'imagepicker' } do
= f.select :apple_touch_icon_image_id, Theme::AppleTouchIconImage.where(company: #company).map{ |i| [i.id, i.id, { 'data-img-src' => i.image.url(:thumbnail) }] }
= f.button :submit, class: "btn-success"
I would try:
= f.input :apple_touch_icon_image do
= f.select :apple_touch_icon_image_id, Theme::AppleTouchIconImage.where(company: #company).map{ |i| [i.id, i.id, { 'data-img-src' => i.image.url(:thumbnail) }] }, {}, { class: 'imagepicker' }

Resources