I want to create a search form for products according to category and sub-category. The user will have to select a category first and then a sub-category. The code that I have written is below:
<%= form_tag('/products/search') do |f| %>
<%= select_tag(:category_id, Category.all.collect { |s| [ s.name, s.id ]} ) %>
<%= select_tag(:subcategory_id, Subcategory.all.collect { |s| [ s.name, s.id ]} ) %>
<div><%= submit_tag 'Search' %></div>
<% end %>
but when I see the page in the browser, I see empty selects. The HTML source returns select with no options as below:
<select id="category_id" name="category_id">
jewellery1beads2pendants3</select>
<select id="subcategory_id" name="subcategory_id">necklace1earrings2taps3</select>
What am I missing?
You can just do this.
<%= select_tag(:category_id, options_from_collection_for_select(Category.all, "id", "name")) %>
Related
I want to filter a drop list items depending on choice item from another drop list
<%= form_tag("/myAdmin", method: "post") do %>
<%= label_tag(:role_id, "Role: ")%>
<%= select_tag('Role', options_for_select(Role.all.map(&:name))) %> <br/>
<%= label_tag(:school_id, "School: ")%>
<%= select_tag('School', options_for_select(School.all.map(&:name) )) %> <br/>
<%= label_tag(:grade_id, "Grade: ")%>
<%= #grade = Grade.all
#grade1 = #grade.map {|a| if a.school_id == :school_id a}
select_tag('Grade', options_for_select(#grade1.map(&:name) )) %> <br/>
<%= submit_tag("Submit") %>
<% end %>
here's a form that contains 3 drop lists.
I want to filter the grade list according the chosen school..
The grade model has { school_id and name attributes } and the school model has { organization_id and name attributes }
how can I do this?
I have following dropdown:
<%= select_tag 'category', options_from_collection_for_select(#categories, "id", "name"), prompt: "Select Category"%>
I am new in rails.I want to show data on the table when i click on any Category from this dropdown.Is there any way to do it only in Ruby code.
Make following changes in your view:
<%= form_tag search_path, :method => 'get' do %>
<%= select_tag 'category', options_from_collection_for_select(#categories, "id", "name"), prompt: "Select Category"%>
<%= submit_tag "Search", :name => nil %>
<table>
<% #object_for_table.each do |object| %>
----YOUR TABLE DATA HERE---
<% end %>
</table>
Changes to action that is responsible for above view:
def search
#object_for_table = params[:category].blank? ? Model.all : Model.where(category_id: params[:category])
end
Finally make changes in your js for submit form on category selection.
$(document).ready(function() {
$("select#category").change(function(){
$(this).closest("form").submit();
});
});
I've got a Rails 2 site I'm trying to add a form handler to, but I'm running into problems converting the html form fields into form handler fields.
The form code begins with:
<% form_for #newsavedmap, :html=>{:id=>'createaMap'} do |f| %>
I keep getting errors when I try things like
<%= text_field :newsavedmap, :html=>{ :value => 'New Map', :name=>'newsavedmapname', :id=> 'savedmap_name', :size => '30' } %>
Error:
ActionView::TemplateError (wrong number of arguments (1 for 2)) on line #284 of app/views/layouts/maptry.html.erb:
Here are the fields. How can I convert these to form handler fields in Rails 2?
<input id="savemap_name" name="newsavedmapname" size="30" type="text" value="New Map"></p>
<select id="startdrop" name="startthere">
<OPTIONS HERE>
</select>
<select multiple id="waypoints" class="mobile-waypoints-remove" name="waypointsselected[]">
<OPTIONS HERE>
</select>
Thanks for any help you can provide!
Edit 1 Error Code for the Text_Field
Using Bigxiang's approach, I get
Processing NewsavedmapsController#create (for IP at Date Time) [POST]
Parameters: {"endhere"=>"", "endthere"=>"SAMPLE ADDRESS 1", "newsavedmap"=>{"newsavedmapname"=>"test Map"}, "startthere"=>"SAMPLE ADDRESS 2", "starthere"=>"", "optimize"=>"on"}
ActiveRecord::UnknownAttributeError (unknown attribute: newsavedmapname)
The line with "newsavedmap"=>{"newsavedmapname"=>"test Map"} should just read
"newsavedmapname"=>"test Map"
How can I do this? My controller starts with:
def create
#newsavedmap = Newsavedmap.new(params[:newsavedmap])
#newsavedmap.name = params[:newsavedmapname]
try this:
<% form_for #newsavedmap, :html=>{:id=>'createaMap'} do |f| %>
<%= f.text_field :newsavedmapname :id=>"savemap_name", :size=>30, :value=>"New Map"%>
<%= f.select :startthere, YOUR_COLLECTIONS, {}, {:id=>"startdrop"}%>
<%= f.select :waypointsselected, YOUR_COLLECTIONS, {}, {:id=>"waypoints", :class=>"mobile-waypoints-remove", :multiple => true}%>
<% end %>
make sure YOUR_COLLECTIONS should be an array like ['a', 'b', 'c'] or [['name1', id1],['name2', id2],['name3', id3]].
If you persist the parameter is "newsavedmapname"=>"test Map", try this:
<% form_for #newsavedmap, :html=>{:id=>'createaMap'} do |f| %>
<%= text_field_tag :newsavedmapname, "New Map", :id=>"savemap_name", :size=>30%>
<%= select_tag :startthere, options_for_select(YOUR_COLLECTIONS), {:id=>"startdrop"}%>
<%= select_tag :waypointsselected, options_for_select(YOUR_COLLECTIONS), {:id=>"waypoints", :class=>"mobile-waypoints-remove", :multiple => true}%>
<% end %>
But I don't understand why not use parameter's name as same as the column's name. For example, I see your newsavedmap model has a column named "name". you can use it directly
<% form_for #newsavedmap, :html=>{:id=>'createaMap'} do |f| %>
<%= f.text_field :name , :value=>"New Map" %>
<% end %>
in your controller , you can delete line #newsavedmap.name = params[:newsavedmapname]
def create
#newsavedmap = Newsavedmap.new(params[:newsavedmap])
if #newsavedmap.save
#######
end
end
I have a form where you have to select any number of courses that are prerequisites for certain classes. Basically, course1 -> list of all courses where you choose which ones are prereqs. Then course2 -> and so on. The forms are perfect, but when I submit it, the params in the next page are in a weird format.
course[1][]:1
course[1][]:2
course[2][]:2
#course is Course.all
<% #course.each do |course| %>
<div>
<%= label_tag "course[#{course.id}]", course.title %>
<%= select_tag "course[#{course.id}]", options_from_collection_for_select(#course, "id", "title"), multiple: true %>
</div>
<% end %>
How can I pass the final params as
course[1]: [1, 2]
course[2]: [2]
Thanks!
Please replace the select tag with below tag and try.
<%= select_tag "course[][#{course.id}]", options_from_collection_for_select(#course, "id", "title"), multiple: true %>
I Hope this will help.
I have two models: Stations & Drinks
Stations has_many :drinks and Drinks belongs_to :stations
I'm trying to make my form so that when you create a station, you can select 4 drinks that will belong to that station as well.
Original form:
<%= semantic_form_for [:admin, #station] do |f| %>
<fieldset class="inputs">
<ol>
<%=f.input :name %>
<%=f.input :number, :as => :number %>
</ol>
</fieldset>
<%= f.buttons :commit %>
I've been trying to figure out how to create 4 (select) input fields in this form so that you can select Drink #1, #2, #3, #4 for the current station. Any ideas?
I'm currently trying accepts_nested_attributes_for :drinks, :allow_destroy => true.
Drinks belongs_to :station
id | name | station_id |
Stations has_many :drinks
id | name |
.
UPDATE
As noted below by tihm, you can add 4 drinks and edit their values with this:
<% f.fields_for :drinks do |drink_form| %>
<%# Put your inputs here...could be a select box %>
<%= drink_form.select :name, [['Drink #1', 'drink_1'],['Drink #2', drink_2] %>
<%# Or a plain input %>
<%= drink_form.input :description %>
<%# ... Any other drink attributes ... %>
<% end %>
However, what I'm trying to do is generate four select boxes that each list Drink.all and be able to swap out one drink object with a different one. So, when you change the value of the first select box from coke to pepsi, it removes the station_id from coke, and adds the station_id to pepsi.
I don't need to be able to edit the drink attributes.. I just need to change which drinks are associated with this station. Is this possible in the same form?
You'll want to start by watching:
http://railscasts.com/episodes/196-nested-model-form-part-1
http://railscasts.com/episodes/197-nested-model-form-part-2
If you know you'll always have 4 or less, then it's a bit easier and you can skip the js from the Railscasts.
In your controller, be sure to build the empty drink objects you need:
....
#station = Station.new
4.times do
#station.drinks.build
end
...
This way, the #fields_for in the view has objects to iterate over. In your view, something ilke:
<%= semantic_form_for [:admin, #station] do |f| %>
<fieldset class="inputs">
<ol>
<%=f.input :name %>
<%=f.input :number, :as => :number %>
<% f.fields_for :drinks do |drink_form| %>
<%# Put your inputs here...could be a select box %>
<%= drink_form.select :name, [['Drink #1', 'drink_1'],['Drink #2', drink_2] %>
<%# Or a plain input %>
<%= drink_form.input :description %>
<%# ... Any other drink attributes ... %>
<% end %>
</ol>
</fieldset>
<%= f.buttons :commit %>
The #select will depend a lot on what you are selecting from and the structure of that data. Is it coming from a model, a simple list, etc.
Unfortunately, I couldn't find a "best-practice" rails way of doing... so I ended up doing a bunch of AJAX / custom ruby code to implement it. Here it is (maybe it'll help someone else):
<% #drinks = Drink.all %>
<fieldset class="inputs">
<ol>
<% #station.drinks.each_with_index do |d,i| %>
<li>
<label class="label" for="station_name">Item</label>
<%=select("drink", "id", #drinks.collect { |d| [d.name,d.id] }, {:include_blank => true, :selected => d.id}, {:class => "station-items"})%>
</li>
<% end %>
<% m = 4-#station.drinks.count %>
<% m.times do %>
<li>
<label class=" label" for="station_name">Item</label>
<%=select("drink", "id", #drinks.collect { |d| [d.name,d.id] }, {:include_blank => true}, {:class => "station-items"})%>
</li>
<% end %>
</ol>
</fieldset>
<%= f.buttons :commit %>
<% end %>
<script>
$(".station-items").on("change",function(){
var node = $(this)
, prev = node.attr('data-rel')
, next = parseInt(node.val())
, station_id = $("#station_id").val()
if(next) {
$.ajax({
url: "/drinks/"+next+".json",
type: "PUT",
data: { id:next, "drink[station_id]":station_id }
});
}
if(prev) {
$.ajax({
url: "/drinks/"+prev+".json",
type: "PUT",
data: { id:prev, "drink[station_id]":"" }
});
}
$(this).attr('data-rel',next);
});
$('.station-items option:selected').each(function(){
return $(this).parent().attr('data-rel',$(this).val())
});
</script>