Defaults not set in Rails multiple-select form - ruby-on-rails

In my application, one article can have multiple tags. When creating an article, I am able to add multiple tags to an article using a multiple-select dropdown and the Rails Select2 gem.
The problem is that when I edit the article, none of the tags are selected, and a user has to select them all over again.
<%= form_for(#article) do |f| %>
<%= f.select :tags, options_for_select(#tags.collect {|t| [ t.id, t.title] }),{:selected=>#article.tags}, :multiple => true, :id => "article_tags", :class => "form-control" %><br>
<%= f.submit 'Update', :class => "btn" %><br>
<% end %>
<script>
$(document).ready(function() {
$("#article_tags").select2({multiple:true});
});
</script>
Any suggestions?

This ended up working when I put it at the bottom of the page:
<script>
$(document).ready(function() {
$("#tags").select2({multiple:true});
$('select').select2().select2('val', 'tag one, tag two, tag three');
$('select').select2();
});
</script>

Related

select2-rails + act_as_taggable_on rails 4 issue

I installed select2-rails and act_as_taggable_on gem to my app. I setup the act_as_taggable_on and it works (I tested from the console). However, when I tried to create the view so that user can add new tag, it's not working.
I want to make a tagging support like this: https://select2.github.io/examples.html#tokenizer.
Here is my setup:
apps/assets/application.js
$(document).ready(function(){
$(".multiple-input").select2({
theme: "bootstrap";
tags: true;
tokenSeparators: [',']
})
});
apps/views/profiles/new.html.erb
<%= form_for #profile, url: user_profile_path do |f| %>
<%= f.text_field :name, placeholder: "Full Name" %>
<%= f.text_field :skill_list, placeholder: "Skills", class: 'multiple-input' %>
<% end %>
When I open the profiles/new on my browser, the skill_list text field show as the way it is instead of using select2 tagging system.
There must be something wrong or missing with my code. Please help.
Update 1
I changed the code to:
<%= f.select :skill_list, placeholder: "Skills", class: 'multiple-input' %>
No luck.
So, I installed simple form gem because based on this article (http://onewebstory.com/notes/user-friendly-tagging-on-rails) select2 rails won't work with select tag.
Here is my current code:
apps/views/profiles/new.html.erb
<%= simple_form_for(#profile, url: user_profile_path) do |f| %>
<div class="form-inputs" %>
<%= f.input :name, placeholder: 'Full Name' %>
<%= f.input :skill_list, input_html: { class: 'multiple-input' } %>
</div>
<% end %>
apps/assets/application.js
$(document).ready(function() {
$('input.multiple-input').each(function() {
$(this).select2({
theme: 'bootstrap',
tags: $(this).data('tags'),
tokenSeparators: [',']
});
});
});
The select2 is working, I can use the select2 search and dropdown. However I want it to be tagging input and every time the user inputs comma (,) temporary stored just like in here :(https://select2.github.io/examples.html#tokenizer)
It's working now. I did it with this code: https://stackoverflow.com/a/33035355/5081949
Here is my code now:
app/views/profiles/new.html.erb
<%= f.input :skill_list, input_html: { class: 'multiple-input', multiple: "multiple" }, collection: #profile.skill_list %>
app/assets/application.js
$(document).ready(function() {
$('.multiple-input').each(function() {
$(this).select2({
tags: true,
tokenSeparators: [','],
theme: 'bootstrap',
placeholder: 'Separated by comma'
});
});
});
also in apps/controllers/profiles_controller.rb I added strong params
def profile_params
params.require(:profile).permit(:name, skill_list: [])
end

Rails: if certiain value in form is selected, then populate another text_field

There is probably a simple solution for this, however, I couldn't find it.
I have a simple form where I have state select box & site text_field:
_form.html.erb
<div class="field">
<%= f.label :state, 'State' %><br>
<%= f.select :state, [['NSW'], ['VIC'], ['SA'], ['WA'], ['QLD']] %>
</div>
<div class="form-group">
<%= f.label :site, 'Site'%><br>
<%= f.text_field :site %>
</div>
I would really like to be able to select "VIC" (a state in Australia) and then due to the fact that "VIC" was selected, the :site text_field is automatically populated with another value such as a site name.
For example: "VIC" state is selected -> "Melbourne" site is populated in the text_field on the form (in :site)
I have played around a bit with some example javascript that I have found on the web which seems to update some text on the screen when a certain value is chosen in a select box, however, I cannot seem to form an "if" argument that states: if "VIC" selected, then populate text_field of :site with "Melbourne".
Thanks in advance.
code for javascript that changes to the value selected:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
<div id="text_to_be_changed"><%= #day_of_week %></div>
<%= select_tag :days, options_for_select(["Monday", "Tuesday"]), :id => "select_days" %>
<script>
$(document).ready(function(){
$('#select_days').change(function() {
$('#text_to_be_changed').html($(this).val());
});
});
</script>
You can try this:
<script>
$(document).ready(function(){
$('#select_days').change(function() {
$('#text_to_be_changed').html($(this).val());
});
// adding pre-populate data
$("#configfile_state").change(function(){
var selected = $(this).val();
if(selected == "VIC") {
$("#configfile_site").val("Melbourne");
}
});
});
</script>
I hope this help you.
You will need the javascript to "know" the relationship between "VIC" and "Melbourne", or more generally between states and their capital cities. This can be stored in a variety of ways, eg as an array or map in your js code. eg
html:
<div class="field">
<%= f.label :state, 'State' %><br>
<%= f.select :state, [['NSW'], ['VIC'], ['SA'], ['WA'], ['QLD']], :id => "state-select" %>
</div>
<div class="form-group">
<%= f.label :site, 'Site'%><br>
<%= f.text_field :site, :id => "city-select" %>
</div>
js:
$(document).ready(function(){
var stateDefaultCities = {
"VIC": "Melbourne",
"NSW": "Sydney",
"WA": "Perth"
//etc
}
$('#state-select').change(function() {
$('#city-select').val(stateDefaultCities[$(this).val]);
});
});
EDIT: this solution is a bit fragile since the states are repeated in the markup and html: eg if you were to add an option to the select you'd need to add a corresponding line to the stateDefaultCities object. But it's just an example.

create form fields on the fly from drop down

I dint even understand how to search for my problem scenario in google.
Problem : When a user selects from a drop-down, the below form fields should change accordingly.
Example : If a user selects "Human" from Drop-down , then below form_fields should be shown like "age" field ,"ethnicity" field etc..
If a user selects "Event" from drop-down, below form fields should show "Date", "venue" etc..
and By default we will have "SUBMIT" button.
Can anyone tell how to achieve this ? Any help with simple_form ruby gem also would be helpful.
You can do this with some simple javascript. Lets say you have a form with the following fields
<%= f.select :some_field, %w[Human Cat], {}, {:class => 'my-select'} %>
<div class="human">
<%= f.label :age %><br>
<%= f.text_field :age %>
</div>
<div class="cat" style="display:none;">
<%= f.label :sub_species %><br>
<%= f.text_field :sub_species %>
</div>
Now add some javascript to make it dynamic
<script>
$(".my-select").change(function(){
if($(".my-select").val() == "Human"){
$(".human").css('display', 'block');
$(".cat").css('display', 'none');
}else{
$(".human").css('display','none');
$(".cat").css('display', 'block');
}
})
</script>
This is quite easy to achieve with the simple_form gem and some simple javascript.
View
<%= simple_form_for #object do |f| %>
<%= f.input :attribute_name, :collection => ['Human', 'Event'], :input_html => { :class => 'dropdown' %>
<div class="toggle human" style="display:none;">
<%= f.input :age %>
</div>
<div class="toggle event" style="display:none;">
<%= f.input :date %>
</div>
<%= f.button :submit %>
<% end %>
The key here is wrapping the fields you want to toggle in div with specific selectors.
Then we look for a change event on the dropdown field, and toggle our divs accordingly.
Javascript
$('.dropdown').change(function() {
// hide divs first
$('form .toggle').hide();
// get value from dropdown
var divClass = $('.dropdown').val().toLowerCase();
// show necessary div
$('.' + divClass).show();
});
Using this approach, you don't need to write the specific case for every value of the dropdown, but can use the lower case value of the dropdown as the selector for the div.
Here is a simple example with static markup.

How to pass collection_select value with link_to_remote in rails?

I want to pass collection_select drop down list value with link_to_remote.
<%= collection_select("event", "trainer_id", #trainers , :id, :name, {:prompt => true}) %>
<%= link_to_remote 'Show calendar', :url => {:controller => 'calendar', :action => 'trainer_view'} %>
I want to pass the selected trainer_id value to the trainer_view method. How can I do this?
Hi :) I would recommend using jQuery and AJAX to accomplish your goal, this is how I would try to do it:
First, I would drop the <%= link_to_remote %> under the collection_select so it would look like this:
<%= collection_select("event", "trainer_id", #trainers , :id, :name, {:prompt => 'Select a Trainer'}) %>
<div id="trainerCalendar"></div>
Then, put this JavaScript in your application.js, when the DOM is ready:
$('#trainer_id').live('change', function() {
$('#trainerCalendar').html.empty;
$.ajax({ url: '/trainer_view/',
data: 'id=' + this.value,
success: function(data) {
$('#trainerCalendar').html(data);
}
})
});
You can have your controller respond with a partial of the calendar.
Hope this helps!

passing text_field values in ajx on rails

I'm using
<%= text_field 'person', 'one',:id => 'test', :onchange=>remote_function(:url=>{:action=>"update"}, :update=>"test") %>
<div id="test"></div>
Now I just want to send the value of text_field with :action
i.e :url=>{:action=>"update(value_of_text_field_entered"}
Don't want to use params[:person][:one].
Any suggestions?or how can I use <%= observe_field %> to send the value with action?
You can try this one also:
<%= text_field 'person', 'one' %>
### Paste following code in your javascript
$("#person_one").live("change", function(){
$.ajax({
complete:function(request){},
data:'person_one='+ $(this).val(),
dataType:'script',
type:'get',
url: '/update'route
})
});
maybe you can use a javascript code, "this.value()"
Use
<%= text_field 'person', 'one',:id => 'test' %>
<%= observe_field 'persone_one',
:url=>{:action=>"update"} ,
:frequency => 0.25,
:update=>'test',
:with => 'person_one'
%>
<div id="test"></div>
you get value of textfiled in params[:person_one]

Resources