Rails form mix checkboxes and radio buttons on same parameter - ruby-on-rails

In my form I have :option_ids which passes a list of IDs back to the model to build associations with the applicable Options. In my case there are groups of options allowing the user to select any combination of options.
Currently I have this in my form:
- #option_groups.each do |group|
- unless group.options.blank?
.form
h3 = group.name
.checkboxes
= line_item.collection_check_boxes :option_ids, group.options, :id, :name_and_price do |option|
.checkbox.horizontal
= option.check_box(class: "check")
= image_tag option.object.photo.variant(resize: "65x65") if option.object.photo.attached?
= option.label
Recently we added a condition to the OptionGroup model allowing users to define whether multiple options from this OptionGroup could be selected(checkboxes), or only one(radio buttons).
What I'm wondering is if there's a way I can still populate the :option_ids parameter using a combination of checkboxes and radio buttons. I've tried the following but it messes up the params hash
-#option_groups.each do |group|
- unless group.options.blank?
.form
h3 = group.name
- if group.multiple?
.checkboxes
= line_item.collection_check_boxes :option_ids, group.options, :id, :name_and_price do |option|
.checkbox.horizontal
= option.check_box
= image_tag option.object.photo.variant(resize: "65x65") if option.object.photo.attached?
= option.label
- else
span Please select one
.checkboxes
= line_item.collection_radio_buttons :option_ids, group.options, :id, :name_and_price do |option|
.checkbox.horizontal
= option.radio_button
= image_tag option.object.photo.variant(resize: "65x65") if option.object.photo.attached?
= option.label
Has anyone encountered a scenario like this before? How would someone conditionally impose exclusivity while not messing up the other id's in the form attribute?

Related

Create a like method for filter query on Rails, smart_listing gem

I want to filter the content of a table who i created with smart_listing gem
For the unknown, SmartListing also known as smart_listing is a Ruby Gem that provides a tools to create lists on your Rails app
I can use the pagination but the filter still not working
Link to smart_listing documentation for Controls (filtering) documentation section
In the docs says that:
# Apply the search control filter.
# Note: `like` method here is not built-in Rails scope. You need to define it by yourself.
users_scope = users_scope.like(params[:filter]) if params[:filter]
This is my code, how i can make runs the filter? I have this on the controller
if !current_user.current_organization.import_columns.nil?
#import_contacts = UserImport.where(organization_id: current_user.current_organization.id)
#import_contacts_column_filter = current_user.current_organization.import_columns.split(/,/)
contacts_import_scope = #import_contacts
contacts_import_scope = contacts_import_scope.like(params[:filter]) if params[:filter]
#contacts_import_scope = begin_of_association_chain.order('active DESC')
#contacts_import_scope = contacts_import_scope.imported_users_filter(params[:filter].strip) if params[:filter]
#import_contacts_listing = smart_listing_create(
:import_contacts,
contacts_import_scope,
partial: 'contacts/listing_import',
default_sort: {created_at: "desc"}
)
end
This on the Views
index.html.slim
.tab-content
- if #import_contacts.any?
.search-wrapper.pull-right
= smart_listing_controls_for(:import_contacts) do
span.btn.pull-right
i.fa.fa-search
.filter.input-append.pull-right
= text_field_tag :filter, '', class: 'search', placeholder: "#{t('commons.filters.search_pending_petition_contacts')}", autocomplete: 'off'
_listing_import.slim
- unless smart_listing.empty?
.pending_contacts_table.table-responsive
table class="table-striped table-list" style="width: 100%; background-color: #FAFBFD;"
thead
tr
- #import_contacts_column_filter.each do |column|
th.name.col-sm-2 = smart_listing.sortable "#{column}", "#{column}"
th.name.col-sm-2 Añadir
tbody
- smart_listing.collection.each do |user_imported|
tr
- #import_contacts_column_filter.each do |field|
td = "#{user_imported.send(field)}"
td
- if User.exists?(email: user_imported.email)
p Ya añadido
- else
- last_name = "#{user_imported.surname1}"+"#{user_imported.surname2}"
= link_to new_organization_customer_path(name: user_imported.name, last_name: last_name, email: user_imported.email, tmp_pass: user_imported.tmp_pass), class: 'btn btn-success' do
i class='fa fa-plus-square'
= page_entries_info smart_listing.collection
= smart_listing.paginate
- else
How we define the doc's .like method?
As i wrote on the code and left commented, before i tried to write in this way also without results.
#contacts_import_scope = contacts_import_scope.imported_users_filter(params[:filter].strip) if params[:filter]
Solved!
issue was with the ImportsController, must be defined on it and not on ContactsController.
also controller finally looks as this
def load_import_contacts
#import_contacts_column_filter = current_user.current_organization.import_columns.split(/,/)
#import_contacts = UserImport.where(organization_id: current_user.current_organization.id)
#import_contacts = #import_contacts.where("name Like ? OR surname1 LIKE ? OR surname2 LIKE ? OR reference_number LIKE ? OR email LIKE ? OR mutua LIKE ?", "%#{params[:filter]}%","%#{params[:filter]}%", "%#{params[:filter]}%", "%#{params[:filter]}%","%#{params[:filter]}%", "%#{params[:filter]}%") if params[:filter]
#import_contacts_listing = smart_listing_create(
:import_contacts,
#import_contacts,
And _listing_import.slim...
#import_contacts = #import_contacts.where("name Like ? OR surname1 LIKE ? OR surname2 LIKE ? OR reference_number LIKE ? OR email LIKE ? OR mutua LIKE ?", "%#{params[:filter]}%","%#{params[:filter]}%", "%#{params[:filter]}%", "%#{params[:filter]}%","%#{params[:filter]}%", "%#{params[:filter]}%") if params[:filter]
Finally, filter and pagination works!

How to push a blank name and a name on to this array in Rails

I have an array of names. I want the first option to be blank, and the last option to be "Joe".
Here is the code:
def index
#case_managers = client.personnel_search_by_client(current_client.client_id, nil, groupMnemonic: 'reimbursement_whitelist')
#case_managers_drop_down = {}
#case_managers.each do |case_manager|
#case_managers_drop_down[case_manager.name] = case_manager.to_json
end
end
In my views I have:
= form_tag work_lists_path, :method=> 'put' do |f|
.fieldset.field-group.field-group-inline.pull-left
.field.field-text.field-required
%label= t('workflow.duplicate_claim_manager')
= select_tag('case[case_manager]', options_for_select(#case_managers_drop_down, #selected_case_manager))
This correctly gets all the names. I thought before the array I would do something like #case_managers_drop_down.push(" ") to get a blank option and then likewise for Joe. But this doesnt seem to be working. Any idea on how I can append to this array?
To get a blank option at first place in select_tag use include_blank boolean attribute like :
= select_tag('case[case_manager]', options_for_select(#case_managers_drop_down, #selected_case_manager), :include_blank => true)
OR use prompt like :
= select_tag('case[case_manager]', options_for_select(#case_managers_drop_down, #selected_case_manager), :prompt => "Please select")
For last option as joe do it like :
def index
#case_managers = client.personnel_search_by_client(current_client.client_id, nil, groupMnemonic: 'reimbursement_whitelist')
#case_managers_drop_down = {}
#case_managers.each do |case_manager|
#case_managers_drop_down[case_manager.name] = case_manager.to_json
end
#case_managers_drop_down["joe"] = ""
end
Hopefully it will work!

Why is a Rails form_tag displaying an array?

Using Rails 3/Ruby 1.9.3, I have to dynamically generate a form using an array of values. The form generates properly with the exception that the #sub_fields array is being output to the screen between the form values and the submit button.
The HAML code that generates the form looks like this:
= form_tag "/magazine/subscribers" do
= #sub_fields.each do |k,v|
.formField
- if v.has_key? :evaluate
= label_tag k.to_s, v[:label_text]
= v[:evaluate].call(k)
- else
- unless v[:input_type] == :hidden_field
= label_tag k, v[:label_text]
- if v[:select_options]
= select_tag(k, options_for_select(v[:select_options].call))
- else
= eval(v[:input_type].to_s + "_tag '#{v[:value].to_s}'")
- if v.has_key? :tooltip
.fieldTip
%ul
- v[:tooltip].each do |tip|
%li= tip
.formAction
= submit_tag "localize edit"
Use - instead of =
- #sub_fields.each do |k,v|

How to extract values from a custom SQL query

I have the following custom query whereby I am trying to extract the values so they are meaningful for my app
#sizes = Product
.joins(:product_properties)
.joins('INNER JOIN variant_properties on product_properties.property_id = variant_properties.property_id')
.joins('INNER JOIN properties ON properties.id = product_properties.property_id AND properties.id = variant_properties.property_id AND properties.display_name = \'Size\'')
.joins('INNER JOIN variants on variants.product_id = products.id AND variants.id = variant_properties.variant_id')
.pluck('products.id as prod_id', 'LEFT(variant_properties.description,1) as short_desc', 'variants.price as price')
below is the code within my view
- #sizes.each do |size|
- size.each do |var|
= var.price
= link_to var.short_desc, product, class: 'hollow button tiny'
%small= number_to_currency(var.price)
Problem is I am getting an error either stating no fixed num or no defined methods
Got it, pluck will return an array of arrays so you cannot call its elements like calling methods. It should be size[0], size[1]... instead.
For the ease of use I suggest you build a hash for this:
#product_sizes = #sizes.each_with_object({}) do |size, result|
result[size[0]] = {
'short_desc' => size[1],
'price' => size[2]
}
end
Then use it in your view:
- #products.each_with_index do |product, i|
.product-list.grid-block
.small-8.grid-content.text-center
%h4= product.name.titlecase
- if size = #product_sizes[product.id]
= link_to size['short_desc'], product, class: 'hollow button tiny'
%small= size['price']
Good luck!

Rspec, Rails - how to test helper method that use params hash?

I want to implement a tagging system similar to stackoverflow, there is a box with a tags at top right corner, and also I have links to delete tag from params hash. my method works correctly in browser. But I can't find a way to test it.
def tags_list_with_destroy_links
if params[:tags]
li = ""
p = params[:tags].split("+") # '/tagged/sea+ship+sun' => ['sea', 'ship', 'sun']
p.map do |t|
remove_link = if p.count >= 3
c = p.reject {|item| item == t }
a = c.join("+")
{:tags => a}
elsif p.count == 2
c = p.reject {|item| item == t }
{tags: c[0]}
else
questions_url
end
li << content_tag(:li) do
link_to(t, questions_tags_path(t), class: 'tag') +
link_to( '', remove_link , class: 'icon-small icons-cross')
end
end
ul = content_tag(:ul, li.html_safe)
ul << tag(:hr)
end
end
I've tried:
it 'return list with selected tags' do
#Rails.application.routes.url_helpers.stub(:questions_tags).and_return('/questions/tagged/sea+ship+sun')
#helper.request.stub(:path).and_return('/questions/tagged/sea+ship+sun')
helper.stub(:url_for, {controller:'questions', action: 'index', tags:'sea+ship+sun'} ).and_return('/questions/tagged/sea+ship+sun')
helper.params[:tags] = 'sea+ship+sun'
helper.tags_list_with_destroy_links.should == 'list_with_tags'
end
but it return:
<a class=\"tag\" href=\"/questions/tagged/sea+ship+sun\">sea</a><a class=\"icon-small icons-cross\" href=\"/questions/tagged/sea+ship+sun\"></a></li>
and shoud return remove link as
href="/questions/tagged/ship+sun" without sea
I would appreciate any advice
The params field is going to come back parsed into the correct ruby data structures (hash, array, string, etc). There's no need to manually split items such as +, if there is a nested param it will return as part of the params object:
{tags: ["sea", "ship", "sun"]}
To access your data, or create an assumption about your param data existing in the test, you're going to want to create a stub. You're almost there, try something more along the lines of:
helper.stub!(:params).and_return({tags: ["sea", "ship", "sun"]})
Once you have the params stubbed correctly you can check the output of your helper method to ensure it's validity (this is called the expectation):
expect(helper.tags_list_with_destroy_links).to eq("some_url")

Resources