Rails - Add custom item to select - ruby-on-rails

I have this line of code:
<%= select "family", "num_of_children", (1..10), { :include_blank => true } %>
I would like to add one item at the end of the list. In this case: I want a "more" option as the last item.
How can I do that?

Convert the range to an array, then append 'more' to it:
<%= select "family", "num_of_children", (1..10).to_a << 'more', { :include_blank => true } %>

<%= select "family", "num_of_children", (1..10).to_a + [['more', '11']], { :include_blank => true } %>

Related

Select box doesn't show selected value

I have a select box like this, it works and is saved in the database, but after I refresh the page the selected value doesn't appear as selected. Any suggestions?
.col-md-6
%span.label.label-purple{:style => "pointer-events: none; font-size: 14px"} Country Default
= select_tag :country_default, options_for_select(Location.where(loc_type: "country").map { |country| [country.name, country.loc_code] }),
style: "margin-top: 11px;",
include_blank: "",
class: "country-default select2", data: { select: "select2"}
options_for_select has an optional second argument, which will display your selected option, if one has been selected.
...options_for_select(Location.where(loc_type: "country").map { |country|
[country.name,
country.loc_code]}, #YOURMODEL.country_default)...
Use collection_select instead of select_tag like this:
=collection_select :country, :default, Location.where(loc_type: "country"), :loc_code, :name,
{include_blank: '', selected: 'select2' },
{class: 'country-default select2', style: 'margin-top: 11px;'}
another option is using select to generate select boxes.
See the Action View Helpers Guide

Multiple selected data doesn't appear

I use select2 for multiple select. My problem is, I can select multiple value from json data and I can save this data in related model columns. But when I want to update this model, the selected data doesn't appear.
some part of my json data:
{
- categories:[
- {
id:7,
name:"Eğitim Bilimleri Enstitüsü"
},
- {
id: 8,
name: "Eğitim Yönetim Teftişi ve Planlaması 1. Yarıyıl"
},
...
]
}
I have a Moodle class(it is not inheritance from ActiveRecord, just a class and it has some functions which return json data). I am wondering whether it is right approach.
in the content of my form:
<%= simple_form_for(#period) do |f| %>
...
<%= f.input :moodle_connect_ids, collection: Moodle.categories.map {|p| [ p['name'], p['id'] ] }, input_html: {multiple: true} %>
...
<% end %>
I explicitly set moodle_connect_ids to be an array in my controller:
params.require(:period).permit(..., :moodle_connect_ids => [])
in the content of my .js file:
$("#period_moodle_connect_ids").select2({
placeholder: "Moodle Dönem Bağlantılarını Seçiniz",
multiple: true,
allowClear: true
});
When I select to multiple values and save my model, the column's value looks like this:
> Period.last
=> #<Period:0x007fcf53a4d830
id: 25,
...
moodle_connect_ids: "[\"\", \"85\", \"120\"]"
...
Am I on the wrong way? Have you any suggestion?
I've figured out how to do this issue.
I've added selected option in the f.input:
selected: #period.moodle_connect_ids? ? JSON.parse(#period.moodle_connect_ids).map(&:to_i) : []
the input's last state:
<%= f.input :moodle_connect_ids, collection: Moodle.categories.map {|p| [ p['name'], p['id'] ] }, input_html: {multiple: true}, selected: #period.moodle_connect_ids? ? #period.moodle_connect_ids.map(&:to_i) : [] %>

Can't specify a class with simple_form gem with a block

I have the following form but for some reason, I can't get the HTML class to come appear in the resulting code. The documentation suggests this should work, but they don't have an example that uses a block. I've tried a few different things but I haven't found the right answer yet. I have to use a block to get the custom data to appear with the select.
= simple_form_for([:admin, #theme]) do |f|
= f.input :title_bar
= f.input :apple_touch_icon_image, input_html: { class: 'imagepicker' } do
= f.select :apple_touch_icon_image_id, Theme::AppleTouchIconImage.where(company: #company).map{ |i| [i.id, i.id, { 'data-img-src' => i.image.url(:thumbnail) }] }
= f.button :submit, class: "btn-success"
I would try:
= f.input :apple_touch_icon_image do
= f.select :apple_touch_icon_image_id, Theme::AppleTouchIconImage.where(company: #company).map{ |i| [i.id, i.id, { 'data-img-src' => i.image.url(:thumbnail) }] }, {}, { class: 'imagepicker' }

search items by category_id with select_tag drop down in rails

I have edited my first code and now it's better and cleaner thanks to #FunTimeFreddie, but the issue it's not yet properly solved. I'll come back with the right answer sooner.
In a search form I need to filter all menuitems:
1. per category
2. per category and search “query”
3. per min price && || max price
… and so on, with all possible combinations
I’ve manage to make a search in all menuitems with a “query”, min_price and max_price --all possible combinations from the search form. I can NOT manage to have the list of results of the chosen category, what am I doing wrong?
This is my model(edited):
class Menuitem < ActiveRecord::Base
belongs_to :menu_category
include Filterable
scope :newest_first, lambda { order('menuitems.created_at DESC') }
scope :last_one, lambda { order('menuitems.created_at ASC').last }
scope :search_keyword, lambda { |query|
where(["title LIKE ? or body LIKE ?", "%#{query}%", "%#{query}%"]) if query != ""
}
scope :menu_category_id, lambda { |menu_category_id|
where( "menu_category_id = ?", menu_category_id ) if menu_category_id != ""
}
scope :min_price, lambda { |price|
where("price > ?", price) if price != ""
}
scope :max_price, lambda { |price|
where("price < ?", price) if price != ""
}
end
This is my controller(edited):
class MenuitemsController < ApplicationController
def index
#menuitems = Menuitem.newest_first.filter(params.slice(:menu_category_id, :search_keyword, :min_price, :max_price))
end
And this is my view:
<%= simple_form_for :menuitem, :method => 'get', :url => {:action => 'index'} do |f| %>
<p>
<%= f.select :menu_category_id, options_for_select(#menucategories.map {|s| [s.title, s.id]}, params[:menu_category_id]), :selected => params[:menu_category_id], :onchange => "this.form.submit();", prompt: "Select category" %>
</p>
<p>
<%= f.input :search_keyword, input_html: { name: 'search_keyword', :value => params[:search_keyword]}, label: 'search recipe title', :required => false %>
<%= f.input :min_price, input_html: { name: 'min_price', :value => params[:min_price]}, label: 'min price:', :required => false %>
<%= f.input :max_price, input_html: { name: 'max_price', :value => params[:max_price]}, label: 'max price:', :required => false %>
<%= f.button :submit, "search" %>
</p>
<% end %>
You can save yourself the trouble of all the IF statements in your controller for all of the combinations by adding an IF statement within the scopes. For example, and this can similarly be applied to the four scopes associated to your form,
# menuitem model
scope :search_keyword, lambda { |query|
where(["name LIKE ?", "%#{query}%"]) if query != ""
}
This will allow to include only a single line in your controller, the line beneath your first IF statement, as this will handle the blank parameters.
There seems to be two issues with the category parameter. The first is it is a nested parameter within params[:menuitem], so in order to access it we need to call params[:menuitem][:menu_category_id]. Not too sure why this is happening to be honest, though I would recommend in this instance using a form_tag as opposed to form_for, given that we are not adding or editing the menuitems table itself.
The second issue is the category parameter is passed as a string, whereas we need it as an integer. We'll need to convert to parameter before applying it.
Now I'm not familiar with the .filters method (is this part of a gem?) but I got this to work the old fashioned way just by concatenating all the scopes together in one line as follows...
# menuitems controller
def index
#menuitems = Menuitem.newest_first.min_price(params[:min_price]).max_price(params[:max_price]).search_keyword(params[:search_keyword]).menu_category_id(params[:menuitem][:menu_category_id].to_i)
end
Note, another way of changing the data type would be to do so in the scope. You could do this as follows
# menuitem model
scope :menu_category_id, lambda { |menu_category_id|
where( "menu_category_id = ?", menu_category_id.to_i ) if menu_category_id != ""
}

radio_button selection

Using Haml 3.1.4 (Separated Sally)
I am curious as to what I am doing wrong.
Why does this not show the first radio button selected?
btw, at execution, #organization.pdf_size does equal 'letter_size'
I would actually like the radio button selected based on the
#organization.pdf_size, however I am just trying to get a hard
coded selection to work atm. tyfyt
= form_for [#organization] do |f|
Select a PDF page size
= label_tag 'Letter (8.5x11)'
= f.radio_button :pdf_size, id: 'letter_size', :checked => true
= label_tag 'Half Legal (8.5x7)'
= f.radio_button :pdf_size, id: 'half_legal_size'
= f.submit 'Save', class: 'button'
I have also tried other examples I have seen on stackoverflow, in this fashion:
= f.radio_button :pdf_size, id: 'letter_size', :checked => #organization.pdf_size == 'letter_size' ? true : nil
Try this:
= f.radio_button :pdf_size, "value", id: 'letter_size', :checked => true
As documented here, the radio button needs a value before the options.
Remember to change "value" to something that makes sense for your application.
Try appending this to your link:
input_html: {checked: true}

Resources