Ruby on rails cant get values from textfield to array - ruby-on-rails

I need to get an array of strings from f.text_field and store it into a database.
<div>
<%= f.label :name %>
<%= f.text_field :name %>
</div>
<div>
<%= f.label :tags %>
<%= f.text_field :tags%>
</div>
tags is an attribute and it is in an array. Name stores into the database correctly but nothing to tags.
How can i do this?
Thanks

You'll probably want to either parse that on the client side with JS to create an array that gets stored in a hidden field, or something similar. Alternatively, you should pass the raw text to the controller and parse it ruby. You should probably do the latter as you will probably want to sanitize the input.

There is a very good gem available for handling tagging. It's called acts-as-taggable and is found here https://github.com/mbleigh/acts-as-taggable-on

Related

form for helper bad collection

I am useing a form_for helper to collect data on the client side of my application. However something weird is happening. I am not collecting the :name and :description and they are both returning as nil. this is my code:
<%= form_for #type do |f| %>
....
<%= f.text_field :name, :class => "col-xs-4" %>
<%= f.text_field :description, :class => "col-xs-4" %>
<%= f.submit %>
....
Do I need to make a fields_for under the form_for to get this working? It is a bit tricky because I am using #type which in this case is set up to tell the view which kind of attr. they are looking at. For example, this line:
<%= f.label #type %> <label> Description</label>
depending on what view you are on shows ether:
Group Description
or
Tag Description
and because they are both technically the same, I am using the same index for both. I hope I am clear with my issue and thank anyone who understands my problem and solution.
The param name will depend on the object you pass.
If #type contains an instance of Group, then you will get the params under params[:group], and if it is an instance of Tag, the you will get them on params[:tag]
<%= form_for #type do |f| %>
<%= f.label :name, "#{#type.model_name} Description" %>
<%= f.text_field :name %>
<%= f.submit %>
<% end %>
Note the label definition. The way you are defining it will create 2 labels and the second one will not be linked to any field.
fields_for is normally used when you are creating several objects within the same form, for instance a Project and several tasks associated to it.
Hope this helps.
update:
If #type is a string or symbol it should work too. The tradeoffs using this approach will be that if there are any validation errors when creating the object, those will not be displayed and the fields will not be prefilled with the input that the user gave before submitting the form, forcing the user to enter all the information again and guessing which was the validation error (you can initialize it from the received params, but that complicates the code readability)
The unique thing different in your view would be the label definition.
<%= f.label :name, "#{#type} Description" %>

difference between text_field and text_area in form_for

So I have seen examples of text_field and text_area being used in forms like this:
<%= form_for :account do |a| %>
Name: <%= a.text_field :name %><br />
Password: <%= a.text_area :password %><br />
Password Confirmation: <%= a.text_field :password_confirmation %><br />
<%= a.submit %>
<% end %>
I don't understand the difference, though. Is it necessary for a beginner Rails developer to understand the difference?
I found some explanations in the API which I don't understand - perhaps somebody can take a look and let me know what is going on.
For "text_area":
text_area(object_name, method, options = {})
Returns a textarea opening and closing tag set tailored for accessing a
specified attribute (identified by method) on an object assigned to the template
(identified by object).
Additional options on the input tag can be passed as a hash with options.
Then, for "text_field":
text_field(object_name, method, options = {}) Link
Returns an input tag of the “text” type tailored for accessing a specified
attribute (identified by method) on an object assigned to the template
(identified by object). Additional options on the input tag can be passed
as a hash with options. These options will be tagged onto the HTML as an
HTML element attribute as in the example shown.
a.text_field :name is parse to the following html
<input type="text" name="name">
a.text_area :name would parse to something like:
<textarea rows="4" cols="50">
</textarea>
depending on the options passed.
The simplest way of looking at it is text_field gives you a place for a single line of text, where text_area gives an area for multiple lines.
you can pass a hash of options to the text_area helper to specify the number of rows and columns.
In the example you give above, it would be poor practice to use either text_field or text_area for passwords, you'd be better to use a.password_field
thats a good answer - funny when googling this and looking for a spot on example - after i read the response above - i looked at my code and realized it was an even better example
<%= f.label :name %>
<%= f.text_field :name %><br />
<%= f.label :bio %>
<%= f.text_area :bio %><br />
makes sense, name would only need a single line (unless you have a super long name) where as bio, would need multiple lines.

RoR MongoDB Arrayfield usage

i'm new to MongoDB and unsure how to use the Array-Field-Type.
So i created in my model
field :admins, type: Array
in this field i wanna store all user_ids that are "admins" of the model. But when I try to set this field, it doesnt save the Information in the Array it just simple creates an String with the ID. And due to my constrain that only Admins can edit my filter function
def check_if_admin
unless Agency.find(params[:id]).admins.include?(current_agent.id)
flash[:notice] = "Only possible as Admin."
redirect_to root_path
end
end
gets the error that
"can't convert Moped::BSON::ObjectId into String"
So I tried to initiate my field with in the create def as an array with ID:
#agency.admins = [current_agent.id]
That does the Trick for one user in the Array but how do I add IDs to this field?
When I go into my Edit Form:
<%= form_for(#agency) do |f| %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :admins %><br />
<%= f.text_field :admins %> <br />
</div>
<div class="field">
<%= f.label :agents %><br />
<%= f.text_field :agents %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
And Type in another User_ID by hand, I'm back to my error again.
Anyone knows how to get around that?
Thanks a ton for ur help!
This message means that at some point you stored a string where there should be an ObjectId. Ruby is trying to compare current_agent.id (an ObjectId) with params[:id] (a string).
It seems like you are not converting the input from the text_field in the form to an ObjectID before you push it onto the array.
Take the input from the admins field and make ObjectId's like this:
BSON::ObjectId.new(string_representing_admin_id)
I'm guessing the admins field is a comma separated array of admin _ids and that you are using some _id values that are easy to work with, like a username instead of a generated ObjectId as this would be very burdensome to work with.
In that case you would probably split and strip the input and then make an array of the ObjectIds using a map/select.
It would be much easier to use a select field that displayed usernames for something like this in rails right?
Anyway, show some sample documents from the collection if you need more help.

Rails: Human-friendly date format for text_field

I have a birth_date field that is stored as a datetime value. The default rails form helpers spit out a not-too-friendly format, e.g. "2008-06-10 22:33:19.000000". The below is the vanilla rails way.
<div class="field">
<%= f.label :birth_date %>
<%= f.text_field :birth_date, :size=>"20" %>
</div>
How can I simply apply a format? I tried various approaches, for example strftime should work, I thought. But when I try the following, I get an error undefined method 'strftime' for nil:NilClass
<div class="field">
<%= f.label :birth_date %>
<%= f.text_field :birth_date, :value=>f.object.birth_date.strftime('%m/%d/%Y'), :size=>"20" %>
</div>
Based on some other questions/answers, I tried the following. It works for non-null values, but it is ugly code, and it doesn't work for blank values (actually it shows today's date).
<div class="field">
<%= f.label :birth_date %>
<%= f.text_field :birth_date, :value=> Time.parse(f.object.birth_date.to_s).strftime('%m/%d/%Y'), :size=>"20" %>
</div>
In playing around, it seems that outputting f.object.birth_date is treated as a date, rather than datetime. However, when displayed in the text_field (original, ugly formatting), it includes the time. It is friday afternoon, and my combined lack of familiarity with rails forms and ruby date/time objects is making me feel foolish.
Any simple way to get my form to display nothing if null/blank, and a friendly date otherwise?
If you want a blank string if birth_date is empty, you should simply check that birth_date is non-nil beforehand:
<%= f.text_field :birth_date, :value => (f.object.birth_date.strftime('%m/%d/%Y') if f.object.birth_date), :size => "20" %>
This way, when birth_date is nil, :value gets set to nil.
Have you tried using the date_select form builder helper method? You can also use datetime_select, but it looks like you just want to work with the date here.
<div class="field">
<%= f.label :birth_date %>
<%= f.date_select :birth_date %>
</div>
The API docs are here: http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-date_select
Add on the options you need.
I've always used that approach, or a javascript date selector like this one from jQuery UI. There are plugins for most JS frameworks these days.
If it MUST be a text_field, use a human language date parsing library like chronic. It'll work, but will require that you parse the input from the form somewhere before applying the attribute to your object.

How to set up form for a hash in Rails?

I have some data associated with a model that is in a hash. The hash is generated in the controller: #hash.
What is the proper way to create a form for this data?
I came up with the following code for the view:
<% #hash.keys.each do |key| %>
<div class="field">
<%= f.label key %><br />
<%= text_field_tag "hash_" + key, #hash[key] %>
</div>
<% end %>
This generates the form, but it creates each hash item as a separate variable in the form. This doesn't seem to be the proper way to submit the data back. I would like to get the data back as a hash, and access it with params[:hash].
What is the best way to do this?
Working in Rails 3.07, Ruby 1.9.2.
Thanks.
EDIT: I should have made this clear. This code is inside of a form generated for a model. So, the form needs to submit all the fields for the model, plus the above hash.
Based on this article you should change the name in text_field_tag to
<% #hash.keys.each do |key| %>
<div class="field">
<%= f.label key %><br />
<%= text_field_tag "hash[" + key + "]", #hash[key] %>
</div>
<% end %>
My answer is not strictly on topic but I really recommend you to take a look at http://railscasts.com/episodes/219-active-model. You could use ActiveModel APIs to simulate a model object with Rails 3. Doing that you could simply do something like
<%= form_for(#object) %>
and leaving the populating of your object to Rails APIs.
When you use the helpers that end with _tag that's what happens.
Instead of text_field_tag ... use f.text_field ....
In order to get a hash like params => {:hash => {:field1 => "", :field2 => ""}} you have to pair up form_for with f.input_field_type instead of simply input_field_tag.
See the difference?

Resources