How to get information from a checkbox back into the DB in Ruby - ruby-on-rails

I'm pretty sure I'm being an idiot here, but I've been out of Ruby long enough that my searching isn't coming up with the right answer.
I have a popup with a checkbox. I want, if the user checks the checkbox, to set a flag in the Users table so that the checkbox doesn't come up again.
I already have the code for if the thing is set, the popup doesn't come up. I'm having trouble getting the checkbox state-change back to the DB...
The checkbox code look like this:
%button.btn.btn-primary.slide_show_next{:type => "button", :data => {:toggle => "modal", :target => "#help_slide_show_2", :dismiss => "modal"}}
Next
.show-slideshow
%label
%input.show-slideshow-checkbox{:type => "checkbox", :checked => "checked"}
Show me this when I view a report.
The relevant coffeeScript is:
$ ->
if typeof(gon) != 'undefined' && gon.show_help_slide_show == true && document.cookie.indexOf("show-slide-show=false") == -1
$("#help_slide_show").modal()
if document.cookie.indexOf("show-slide-show=false") != -1
$(".show-slideshow-checkbox").attr("checked", false)
$(".show-slideshow-checkbox").change( (event) ->
val = $(event.target).prop("checked")
document.cookie = "show-slide-show=#{val}; Path=/;"
$(".show-slideshow-checkbox").attr("checked", val)
)

Look into form_for. That will help you update the model from the view. The code for a haml form_for is below, and the erb equivalent can be found in the form_for documentation. I find that haml documentation isn't as robust as I'd like for certain syntax questions.
= form_for #user, remote: true do |f|
= f.label 'checkbox'
= f.check_box :table_column, autofocus: true
= f.submit

Related

get selected items from select_tag

I have this line in my rails app:
<%= select_tag :questionnaire_id,
options_for_select(#questionnaires_types, #questionnaires_ids),
:multiple => true, :size => 7 %>
which works fine.
but when I try to use the multiple values that were selected I get this:
questionnaire_id"=>["1687,1688,1689,1690,1691,1724"]
instead of this:
questionnaire_id"=>["1687", "1688", "1689" ,"1690", "1691", "1724"]
i.e. I get 1 item instead of 6 items.
any suggestions?
According to rails code: https://github.com/rails/rails/blob/41231ef6c6c6a6e546b69add28f04aafb9e0e952/actionview/lib/action_view/helpers/form_tag_helper.rb#L134
The name must end with [] to be make sure you receive an array.
def select_tag(name, option_tags = nil, options = {})
option_tags ||= ""
html_name = (options[:multiple] == true && !name.to_s.ends_with?("[]")) ? "#{name}[]" : name
if options.delete(:include_blank)
option_tags = content_tag(:option, '', :value => '').safe_concat(option_tags)
end
if prompt = options.delete(:prompt)
option_tags = content_tag(:option, prompt, :value => '').safe_concat(option_tags)
end
content_tag :select, option_tags, { "name" => html_name, "id" => sanitize_to_id(name) }.update(options.stringify_keys)
end
So just change it to questionnaire_ids[]
Hope that helps.
I think a collection_select would look nice but I cannot help with that since you did not post anything about the model. Maybe try this so that it knows it is a collection:
<%= select_tag "questionnaire_ids[]", options_for_select(#questionnaires_types, #questionnaires_ids), :multiple => true, :size => 7 %>
Or you could just parse the string you currently receive using #split.
Otherwise post a bit more code about the associations between Questionnaire and what ever this model is.
Well, just in case that someone will come to this issue, I found the problem.
It seems to be a bug in rails.
I was using remote_form_for, and that gave me the strange behaviour. I tried to change the form to form_for instead, and I got an array with 6 items.
Rails, Rails, when will you be like .Net? :-(

Calling a function in application.js after an AJAX request

Spinning my wheels trying to figure this out. I have a link that when clicked retrieves a form from the server. The form has 3 buttons and 1 text input. I'm trying to get the non-submit buttons to respond to JS which they don't do after the form is returned from the server.
I've create a function in lists.js which the ajax:success is trying to call, but I'm not doing something right. I've tested the function in lists.js and I know it works, I'm just not calling it right.
Here are the relevant files. How do I activate the showPicturePicker function so it can be used after the AJAX response is inserted?
Lists.js
$("#new_list")
.bind "ajax:success", (evt, xhr, settings) ->
$("#list-item").html(xhr)
showPicturePicker
showPicturePicker = () ->
$('#picture').click (e) ->
e.preventDefault()
alert "yeah, you figured it out"
$(document).ready showPicturePicker
_new.html.haml (the form returned from the server)
= form_for [#list, #item], :remote => true, :html => {:class => 'form-inline'} do |f|
.input-append
= f.text_field "name", :class => 'input-large', :placeholder => "Add item to this list"
%button#picture.btn
%span.icon-camera
%button#link.btn{:style => "font-size: 10px;"}
http://
.secondary-fields{:style => "display: none"}
.field.margin
= f.text_field "link", :placeholder => "http://www.link.com", :style => "width: 325px"
.field.margin
= f.file_field "picture"
= f.hidden_field "picture_cache"
.clearfix
= link_to "blah", "#{}", :class => "fuck-me"
= f.submit "Add Item", :class => 'btn', :id => "add-item"
This is a problem i'll need to solve in other places as well and I appreciate the help.
application.js is wrapped with an IIFE (immediately invoked function expression) and variables defined there will not be visible in other files unless you explicitly make them available to the global scope (either by attaching them to window or some other object).
In application.js, try:
#showPicturePicker = ->
...
# or window.showPicturePicker = ->
"Although suppressed within this documentation for clarity, all CoffeeScript output is wrapped in an anonymous function: (function(){ ... })(); This safety wrapper, combined with the automatic generation of the var keyword, make it exceedingly difficult to pollute the global namespace by accident."
http://coffeescript.org/#lexical_scope

if condition in haml view

I want to set a :data attr if a condition is met. In this case a user should have a role. So it's a boolean statement. Let me give an example.
- #data = 'contract-confirm'
.create_button= link_to 'Something', new_some_path(#customer), :class => 'btn btn-success', :'data' => #data ? 'contract' : nil
.clearer
So I know this might look strange but I want to set a data attribute if customer is labeled and then hook js to that data attr. That part works. What does not work is that now I'm setting the attribute always. So even in the case that customer does not have the role the js gets hooked. I know that I am not explicitly indicating at all the role here. I have a #customer.role? but I cant seem to incorporate it properply. I managed it before with an if else statement but then with a lot of duplication which I'm not so fund of. Any tips?
You can try this piece of code:
link_to 'Something', ... , :data => #customer.role? ? 'contract' : nil
haml won't include nil attributes, so it should work as you expect.
Try to replace :'data' => #data ? 'contract' : nil with :'data' => 'contract' if #data.
I checked it and next code:
- #data_present = true
= link_to 'Something', root_path, :class => 'btn', :'data' => ('test' if #data_present)
renders to:
Something
And code without - #data_present = true renders to:
Something

How to “dynamically add options” to 'form_for'?

I am using Ruby on Rails 3.2.2. In order to implement a "dynamic generated" AJAX style file upload form I would like to "dynamically add options" to the FormHelper#form_for statement if some conditions are meet. That is, at this time I am using code as-like the following (note that I am using the merge method in order to add options to the form_for method):
<%
if #article.is_true? && (#article.is_black? || && #article.is_new?)
form_options = {:multipart => true, :target => "from_target_name"}
else
form_options = {}
end
%>
<%= form_for(#article, :remote => true, :html => {:id => "form_css_id"}.merge(form_options)) do |form| %>
...
<% end %>
However, I think that the above code is too much hijacked.
Is there a better way to accomplish what I am making? For example, can I access from view templates some (unknown to me) instance variable named as-like #form and "work" on that so to change related options as well as I would like? Or, should I state a helper method somewhere? How do you advice to proceed?
BTW: Since the upload process is handled by using a HTML iframe, I am using the remotipart gem in order to implement the AJAX style file upload form - I don't know if this information could help someone...
This looks like a good candidate for a helper method. In your view:
<%= form_for(#article, :remote => true, :html => article_form_options(#article, :id => "form_css_id")) do |form| %>
...
<% end %>
In app/helpers/articles_helper.rb
module ArticlesHelper
def article_form_options(article, defaults = {})
extras = if article.is_true? && (article.is_black? || article.is_new?)
{ :multipart => true, :target => 'form_target_name' }
else
{}
end
defaults.merge(extras)
end
end
Helpers are a good place to keep logic that's too complex for a view but still related to the view.

Retaining search results after submitting the search (rails)

I'd like to make it so that after users submit their search, the option they selected stays selected upon the search form's reload. Here's my code for one of these select boxes:
<div><%= f.select :tod_like, Course.tod_array, {:include_blank => true, :selected => params[:search][:tod_like], :class=>"float_and_margin"} %></div>
The key code is the
:selected => params[:search][:tod_like]
When I refresh my page, I get the following error:
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.[]
I know I'm getting this error because there's params[:search][:tod_like] is blank. How do I set :selected so that it's blank if the user has not submitted a form, but is the submission, otherwise? I tried using a ternary operator, but that didn't work.
Thanks!
Is the params key correct?
I take it the form f is for an instance of Course so wouldn't it be something like
#course.tod_like = params[:search][:tod_like] ? params[:search][:tod_like] : ""
at the top of the function that generates the search function (you have mentioned that you've tried a ternary statement but did you replace the :selected option at the same time?
Then :selected => #course.tod_like in the select tag?
<div><%= f.select :tod_like, Course.tod_array, {:include_blank => true, :selected => #course.tod_like, :class=>"float_and_margin"} %></div>
Hmm, I ended up fixing this problem by defining a ternary operator in my courses controller, and then passing this instance variable into the appropriate view.
#tod_results = params[:search] == nil ? :blank : params[:search][:tod_like]
<div><%= f.select :tod_like, Course.tod_array, {:include_blank => true, :selected => #tod_results, :class=>"float_and_margin"} %></div>
The key difference between this code and the previous ternary operator I tried is that I'm testing to see if params[:search] is nil, not if params[:search][:tod_like] is nil. Since params[:search] is already nil, I got the "you were expecting an array, but got nil" error when I tried to use params[:search][:tod_like].
Thanks for your responses!

Resources