RoR set value for textarea
<% remote_form_for ... do |f| %>
<%= f.text_area :message, :value => "my default value" %>
<%= f.submit 'Update' %>
<% end %>
Rails edit an array in a text area
Text area helper sends and string containing the content of the input. You need to either parse it before sending the request. Using jQuery normally. Or reparse it into the backend as a valid array.
Eval, as you stated should be working. BUT YOU SHOULD NOT USE IT FOR SECURITY REASONS.
irb(main):004:0> eval("[\"2\"]")
=> ["2"]
In the controller just do:
class FooController < ApplicationController
private
def array_param
eval(param[:array])
end
end
And refer anywhere you need it with: array_param
in the controller methods.
def create
@bar = Bar.new(bar_params.merge({array: array_param}))
#whatever
end
private
def bar_params
params.require(:bar).permit(#everything except the array_param)
end
Textarea in Rails form
Unless you have some good reason not to, you should really use the action view helpers provided by rails.
The form helpers provide resource-oriented methods which create a form and a scope around a specific model object, but this does not suit your case.
What you want instead is to use to use the generic form tag helpers, which include generic versions of the form methods not tied to any specific model or record, e.g.: form_tag
, text_field_tag
, text_area_tag
, etc. These methods do not require you to pass a record to them or define them in terms of a specific model; you can define arbitrary actions, ids etc., like so:
<%= form_tag "submit", :id => "my_form" do -%>
Title: <%= text_field_tag "title" %>
Comment: <%= text_area_tag "comment", :rows => 4, :cols => 50 %>
<%= submit_tag "Submit" %>
<% end -%>
Note that you had no name
or id
on your textarea, so I've arbitrarily assigned them the string "comment"
, which makes sense for the case.
In terms of accessing the value(s) the user enters, you just do it like any other form, i.e. in your controller you just access params[:title]
, params[:comment]
etc.
Textarea Not Sending Value through Form
It'll be hard to come up with a solution since this seems to be a very located problem. So here are just some steps I'd recommend to take in order to nail it down, rather than a shorthand solution:
Check the output of
$('#new_activity_comment').serializeArray()
in the browser console when you are on the actual page with the form in it.This is what the js handling the
data-remote="true"
forms injquery-rails
does to serialize your form data before it sends it to the server.The resulting Javascript
Array
should have an object with name"activity_comment[comment]"
and value"Your comment"
in it.If it does not, your error comes from somewhere in your Javascript or HTML. Where is difficult to say unless you post the JS sources, your
HTML Doctype
etc.EDIT: 1.5. Remove the
"form-control"
class from the textarea and see if it solves your problem. If it does not, try to rip out all the JS coming from Bootstrap and check if your forms are doing ok now. If they are, the problem lies with Bootstrap.Check your Networks tab in the developer tools when you send the request: Your headers should have
FormData
in them and there you should seeactivity_comment[comment]
and your textarea value. If you don't, chances are you're operating on a broken build of jQuery or something with your browser is wrong / you're using a broken build of that, though that is very very unlikely unless you're on some Canary / Alpha Build channel for Chromium or something else.If your Javascript and Browser is sending the form ok and you still get no textarea value in your rails controller, log the contents of the raw rack parameters like that to your rails log:
Rails.logger.info '###' #makes it easier to find your params
Rails.logger.info URI.decode(request.env["rack.request.form_vars"])Now, if
Rack
has the right form value, but rails does not, there are 2 possibilities:- Either there is something messed up in your app with strong parameters, meaning you will have to check for any
params.require
orparams.permit
in yourActivityCommentsController
or anyController
in itsancestors
- There's a bug somewhere in the
Rails
Rack
/ActionController
interface, though that is also highly unlikely. Try to update rails to the latest patch version in that case or try to search forActionController
bugs in theRails
issues on github.
- Either there is something messed up in your app with strong parameters, meaning you will have to check for any
How can I submit a form in RoR whenever an input textfield changes?
Use observe_field helper with a single input, like the code bellow:
<%= text_field_tag 'filter' %>
<%= observe_field 'filter',
:url => {:controller => 'your_controller', :action => 'filter'},
:frequency => 1.2,
:update => 'results',
:with => "'typed_filter=' + $('filter').value" %>
And then just write a controller that, given a param named 'typed_filter', renders the results, wich will be shown in the element with id 'results' (probably a div).
Passing a string to an object in controller using ajax
You should be able to create it like this:
BoothUser.create(user: current_user, booth: @booth, is_admin: true) #add current user
booth_admins.each do |email|
admin = User.find_by(email: email)
BoothUser.create(user: admin, booth: @booth, is_admin: true)
end
In your HTML, you need to create your textarea like this:
<textarea id="create_booth_admins_textarea" name="booth[booth_admin_emails]" rows="30" cols="50"> </textarea>
Then you don't need the JavaScript at all.
...however if you want the entire form to submit via AJAX, then in addition to the HTML changes above, in your JavaScript do this:
$('#booth_create_submit').click(function(e) {
e.preventDefault(); # keeps the HTML form from submitting.
var the_form = $(this.form);
$.ajax({
url: the_form.attr('action'),
data: the_form.serialize(),
type: "post",
cache: false,
success: function () {
console.log("ajax successful");
alert("ajax successful");
},
error: fucntion() {
console.log("ajax error");
alert("ajax error")
}
});
});
Related Topics
How to Sort a Ruby Array by Two Conditions
Ruby Executable Won't Start on Win10 and Win7
Ruby Devise, Sessionscontroller.Create, JSON - Getting Nameerror: Undefined 'Build_Resource'
Rails: How to Pass Custom Params to a Controller Method
Ruby Gets() Not Returning Correct String
Regex to Extract Boundary and Content Type Out of Mail Headers
Why Doesn't This Code Produce the Desired Result
How to Run Code After Ruby Kernel.Exec
Rails How to Use Associated Model with the Admin Namespace
Heroku: Push Rejected, Failed to Compile Ruby App
How to Verify Pacts Against an API That Requires an Auth Token
Can't Find Ffi.H When Installing Ffi Ruby Gem
Check If String Is Repetition of an Unknown Substring
How to Write a Method That Counts the Most Common Substring in a String in Ruby
Ruby on Rails - Helper Method - Undefined Method 'Log_In' in Ruby on Rails
Pow Not Loading Gem Properly While Rails S Works