As title, I have a serialized string column in the model:
class Product < ApplicationRecord
serialize :ingredient_fields, Array
end
The ingrdient_field has many strings, but store in one column within the product model. It is not nested objects.
But I'm not sure how to handle these dynamic text inputs use simple_form, or if I can use cocoon or nested_form_fields to handle the behaviors. I tried many different ways with these gems to generate the html like:
<form>
<input name="product[ingredient_fields][]"> <button>remove</button>
<input name="product[ingredient_fields][]"> <button>remove</button>
<button>add ingredient</button>
</form>
but all failed.
Or I can only write html and js myself?
you can insert index into input names, for example:
<input name="product[ingredient_fields][1]">
<input name="product[ingredient_fields][2]">
so rails will receive an array of products[ingredient_fields]
Related
I am new in ror and I am trying from 4 hours to store the data of form of textfields array like this
<input type="text" name="custom_field[names][]" class="form-control full-width" placeholder = "Name">
<input type="text" name="custom_field[length_limit][]" class="form-control full-width" placeholder = "Length Limit">
I want to store the arrays coming into the form in database columns of name and length limit. I don't want to use loop to do this job.
I am doing this in controller
user = CustomField.create(:name=> params[:names])
But it is giving ERROR: null value in column "name" violates not-null constraint DETAI
params are
{"names"=>["tester", "another tester"], "length_limit"=>["aaaaaa222", "aaaaaa222"]
I am using postgresql
How can I do this?
params[:names] is an array, so it doesn't make sense to save it to a string/text field in postgres, which is what CustomField.create(:name=> params[:names]) does.
Essentially, it expands to CustomField.create(:name=> ["tester", "another tester"]). If you want to create a separate CustomField record for each name, then you could do something like:
params[:names].each do |name|
CustomField.create(:name => name)
end
To create the CustomField records with the corresponding length_limit, you could do something like:
params[:names].zip(params[:length_limit]).each do |name, limit|
CustomField.create(:name => name, :length_limit => limit)
end
Note that this doesn't account for errors where the names and length_limits don't match. You might want to add some validation to make sure that all the required data is present.
I'm making an input form whose features don't fit so nicely into the general form_for template rails provides. I figured I would write my own HTML mimicking the html output of form_for, but embedded with other form_for elements.
For fields I could use the rails framework for I did. For the others I made hidden fields to store what was going to Rails, and regular input fields whose values I manipulated with JavaScript to put into the hidden fields.
This is one such field:
State:<br>
<input type="text" class = "state name_input administrative_area_level_1">
<div class="field">
<input type="hidden" name="address[state]" id="state">
</div>
When I send the value of the hidden field to the console, I get a good response:
state 37
Which means the state field holds the value 37. Perfect.
Except that when I try to make my model, the params come in empty:
"state"=>"",
I do have one field that works that isn't hidden:
Street:<br><input type="text" id="street" name="address[street]">
So I changed the state input type to number, which is what it would be if it weren't hidden, but same result. Why can't rails find my param?
You can show post more detail. I can't understand 100% things you do because you write pretty simple. But i guess that you need test params name is address[state] but it's not only state becase if only state of course it nil.
if html of you rendered same up then i suggest you should put one debug in controller to see params return controller when submit form.
For example: in controller you add line:
logger.debug params
to see right params that form send.
If your form is not tied directly to a object model, it might be difficult to use the form_for helper. In those cases you should use form_tag helper. Read more about form_tag helper here.
Refer this stackoverflow answer for the difference between form_for and form_tag helpers.
Hope this helps.
I have a checkbox
<%= f.check_box :anonymous %>
And my table has a column anonymous which is true or false.
Code generated in html:
<input name="comment[anonymous]" type="hidden" value="0" />
<input id="comment_anonymous" name="comment[anonymous]" type="checkbox" value="1" />
Now, for some reason when I add data it's not saving if my anonymous checkbox is checked or not.. it's not changing data in database.. All other fields gets saved except anonymous.
What can be the problem ?
Use #check_box_tag instead:
<%= check_box_tag(:anonymous) %>
From the official guides:
Array parameters do not play well with the check_box helper. According
to the HTML specification unchecked checkboxes submit no value.
However it is often convenient for a checkbox to always submit a
value. The check_box helper fakes this by creating an auxiliary hidden
input with the same name. If the checkbox is unchecked only the hidden
input is submitted and if it is checked then both are submitted but
the value submitted by the checkbox takes precedence. When working
with array parameters this duplicate submission will confuse Rails
since duplicate input names are how it decides when to start a new
array element. It is preferable to either use check_box_tag or to use
hashes instead of arrays.
I have created model, controller and view with rails scaffold generator:
rails g scaffold Todo description:string tags:array
So I have the model:
class Todo
include Mongoid::Document
field :description, :type => String
field :tags, :type => Array
end
And controller:
def create
#todo = Todo.new(params[:todo])
#todo.save
But this case (auto-generated code) I get error that tells me something like:
tags field must be array datatype, but you're trying to use string
So I have fixed the controller:
def create
##todo = Todo.new(params[:todo])
#tmp = params[:todo]
#tmp["tags"] = #tmp["tags"].split(',')
#todo = Todo.new(#tmp)
And I'm just wondering if there is any better way to fix my error?
Depends on how your view is structured. From what I see, there must be a single text input or something, into which you input tags, separated by comma. No wonder it comes as a string! In this case your workaround is correct. I would add stripping of leading and trailing whitespace, though.
#tmp["tags"] = #tmp["tags"].split(',').map(&:strip)
To get a real array in params your HTML must look like this:
<input type='text' name='tags[]' />
<input type='text' name='tags[]' />
<input type='text' name='tags[]' />
Where each of these inputs holds a single tag.
I have a form that will have both a dynamic set and a known set of fields. I need a way of storing the dynamic fields in the database and I have decided on storing them in a serialized field, as I will not need to search on the data, and I just need it stored and recalled when needed.
class MyApplication < ActiveRecord::Base
has_one :applicant
belongs_to :member
serialize :additional_fields, Hash
accepts_nested_attributes_for :applicant, :additional_fields
I was thinking of having the form return the fields as an additional_fields_attributes and somehow have the model look after storying the hash into the additional_fields section. Im not sure if I have to go as far as using something like method missing to look after this, or if I should scrap the accepts_nested_attributes_for and handle it on my own.
Does anyone have any thoughts?
Thanks! Ryan
I just tested what you suggest.
You don't need: accepts_nested_attributes_for :additional_fields
Just add in your form html like:
<input name="my_application[additional_fields][first]" type="text" />
<input name="my_application[additional_fields][second]" type="text" />
it will save a Hash with keys: first and second
You could put in your model an array of fields, say in your User model:
FIELDS= ["item1", "item2"]
In your view:
<% User::FIELDS.each do |field|%>
<input name="my_application[additional_fields][<%= field %>]" type="text" />
<% end %>
I ended up using this tutorial http://www.kalzumeus.com/2009/11/17/practical-metaprogramming-with-ruby-storing-preferences/ which worked really well.
Thanks for your help!