if condition in haml view - ruby-on-rails

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

Related

How to get information from a checkbox back into the DB in Ruby

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

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? :-(

Rails: Setting class and data-tag of an HTML attribute with a single rails method

I'm currently working on a tour interface that guides new users around my site. I have a Tour model that has many TourStops, each of which contains information about a section of the site.
Basically, I'd like to write a function for the Tour model that -- when passed the number of a TourStop -- generates the correct class and data attribute for the HTML element it's attatched to. For example, I'd like
<%= link_to image_tag("new_button.png", tour.stop_data(1), :title => 'Add new asset'), new_asset_path %>
to call a function and return something like
def stop_data(order)
" :class => '#{tour_stops.find_by_order(order).name}',
:data => '{:order => order}'"
end
creating a link_to tag like:
<%= link_to image_tag("new_button.png", :class => 'tour_stop_1',
:data => {:order => 1}, :title => 'Add new asset'), new_asset_path %>
The above code doesn't work. Is something like this even possible? If not, what's a better approach I might take?
The image_tag accepts two parameters. A source, and a options Hash.
What you are trying to do is squeezing your return value from stop_data into this options Hash.
In order to get this to work, you first, need to return a Hash from stop_data, and second, make sure you pass only two arguments to image_tag - the source, and the options.
First:
def stop_data(order)
{
:class => tour_stops.find_by_order(order).name,
:data => { :order => order } # you may need order.to_json
}
end
Second:
link_to image_tag("new_button.png", tour.stop_data(1), :title => "Add new asset"), new_asset_path
This looks like it will work, but it won't, since your'e passing three parameters to image_tag.
When you do the following:
image_tag("new_button.png", :class => "tour_stop_1", :data => { :order => 1 }, :title => "Add new asset")
It looks like you're passing even 4 parameters to image_tag, but in fact they are only two. In Ruby, when the last parameter of a method is a Hash, you don't need to wrap the Hash key/value pairs in curly braces ({}), so the example above is essentially the same as
image_tag("new_button.png", { :class => "tour_stop_1", :data => { :order => 1 }, :title => "Add new asset" })
Now, to get your helper to work with image_tag, you need to merge the options, so they become only one Hash.
link_to image_tag("new_button.png", tour.stop_data(1).merge(:title => "Add new asset")), new_asset_path
Again, we're omitting the curly braces when calling merge, because it's only (and therefore last) parameter is a Hash. The outcome is the same as:
tour.stop_data(1).merge({ :title => "Add new asset" })

How to display Rails select field values rather than stored integers in other views

I'm using a select field in a Rails app that is NOT tied to a related model, but stores integer values for a static series of options , i.e.,
<%= select (:this_model, :this_field, [['Option1',1],['Option2',2],['Option3',3],['Option4',4]] ) %>
In a show/ index view, if I want to display the option text (i.e. Option1, Option2, etc) rather than the integer value stored in the database, how do I achieve this?
Thanks for helping a noob learn the ropes!
EDIT
Based on Thorsten's suggestion below, I implemented the following. But it is returning nil, and I can't figure out why.
Invoice model:
##payment_status_data = { 1 => "Pending Invoice" , 2 => "Invoiced" , 3 => "Deposit Received", 4 => "Paid in Full"}
def text_for_payment_status
##payment_status_data[payment_status]
end
Invoice show view:
Payment Status: <%= #invoice.text_for_payment_status %>
In the console:
irb > i=Invoice.find(4)
=> [#<Invoice id: 4, payment_status: 1 >]
irb > i.text_for_payment_status
=> nil
I've tried defining the hash with and without quotes around the keys. What am I missing?
something like this would work:
<%= form_for #my_model_object do |form| %>
<%= form.label :column_name "Some Description" %>
<%= form.select :field_that_stores_id, options_for_select({"text1" => "key1", "text 2" => "key2"}) %>
<% end %>
Update
If you later want to display the text you can get it from a simple hash like this:
{"key1" => "text 1", "key2" => "text2"}[#my_object.field_that_stores_id]
But you better store this hash somewhere in a central place like the model.
class MyModel < ActiveRecord
##my_select_something_data = {"key1" => "text 1", "key2" => "text2"}
def text_for_something_selectable
##my_select_something_data[field_that_stores_id]
end
end
Then you can use it in your views like
#my_object.text_for_something_selectable
There are many possible variations of this. But this should work and you would have all information in a central place.
Update
Ok, I used something similar for our website. We need to store return_headers for rma. Those need to store a return reason as a code. Those codes are defined in an external MS SQL Server Database (with which the website exchanges lots of data, like orders, products, and much more). In the external db table are much more return reasons stored than I actually need, so I just took out a few of them. Still must make sure, the codes are correct.
So here goes he model:
class ReturnHeader < AciveRecord::Base
##return_reason_keys = {"010" => "Wrong Produc",
"DAM" => "Damaged",
"AMT" => "Wrong Amount"}
def self.return_reason_select
##return_reason_keys.invert
end
def return_reason
##return_reason_keys[nav_return_reason_code]
end
end
Model contains more code of course, but that's the part that matters. Relevant here is, that keys in the hash are strings, not symbols.
In the views i use it like this:
In the form for edit:
<%= form_for #return_header do |form| %>
<%= form.label :nav_return_reason_code "Return Reason" %>
<%= form.select :nav_return_reason_code, options_for_select(ReturnHeader.return_reason_select, #return_header.nav_return_reason_code) %>
<% end %>
(Maybe no the most elegant way to do it, but works. Don't know, why options_for_select expects a hash to be "text" => "key", but that's the reason, why above class level method returns the hash inverted.)
In my index action the return reason is listed in one of the columns. There I can get the value simply by
#return_headers.each do |rh|
rh.return_reason
end
If you have trouble to get it run, check that keys a correct type and value. Maybe add some debug info with logger.info in the methods to see what actual data is used there.

Using hyphen in link_to property?

In my Rails app, I need to set a value for a custom data-* attribute on an anchor tag. However, hashes can't have hyphens if I'm not mistaken. I essentially want to do this:
<%= link_to 'Example', example_path, :class => 'something', :data-id => '15' %>
:data-id is not valid, however. What can I do to work around this?
IIRC, for such purposes hashes and strings are equivalent, so you can use "data-id" instead of :data-id. Never checked for this particular method, though, so no guarantees.
I think in Rails 3 you can do
link_to "Click Here", root_path, :data => { :id => #model.id }
for all data attributes.

Resources