how to sort a collection with simple form - ruby-on-rails-3

I'm pulling a list of categories from a model.
In the admin section I want to use it to assign categories to products.
It's working fine but the list shows in the order the categories have been added.
I'd like to sort them alphabetically but I can't suss it out.
I'm sure it's pretty simple (hopefully)
here's my code:
<%= simple_form_for(#game) do |f| %>
<%= f.input :name %>
<%= f.input :description %>
<%= f.input :copy %>
<%= f.input :image %>
<%= f.input :thumbnail %>
<%= f.input :heroimage %>
<%= f.association :category, collection: #categories %>
<%= f.button :submit %>
<% end %>
I tried to add a .sort_by(desc) or just .sort on the collection method but it doesn't change the list.
Cheers

Here is how you should update your code:
<%= f.association :category, collection: Category.order('name ASC') %>
This assumes you want to sort by the category name, in ascending order.

I imagine #categories is assigned as an arel in your controller, can you add an .order("description") to that; e.g.
#categories = Category.order('description')

Related

Rails 3 - Ransack - check_box_tag

Listing Model - belongs_to :area
Area Model - has_many :listings
I'm trying to implement a search using Ransack with check boxes; where user checks selected areas, search returns all the listings of the areas selected.
<%= search_form_for #search do |f| %>
<% areas = Area.all %>
<% areas.each do |area| %>
<%= check_box_tag('q[area_id_eq][]', area.id) %>
<%= area.location%>
<% end%>
<%= f.submit "SEARCH" %>
<% end %>
Console output:
Parameters: {"utf8"=>"✓", "q"=>{"area_id_eq"=>["1", "2"]}, "commit"=>"SEARCH"}
Completed 500 Internal Server Error in 4ms
NoMethodError - undefined method `to_i' for ["1", "2"]:Array:
Just not sure how to implement it to accept multiple check box values.
Instead of using "area_id_eq", use "area_id_any". You'll also want to check to make sure that your parameters are selected:
<%= search_form_for #search do |f| %>
<% areas = Area.all %>
<% areas.each do |area| %>
<%= check_box_tag('q[area_id_eq_any][]', area.id, (params[:q][area_id_eq_any].include? area.id.to_s) ? true : false ) %>
<%= area.location%>
<% end%>
<%= f.submit "SEARCH" %>
<% end %>

Update form in rails - No route matches [PUT]

I have a form to create adverts.
Controllers:
def edit
#engines = Engine.all
#car = Car.find(params[:id])
end
def update
#car = Car.find(params[:id])
if #car.save
redirect_to root_path
end
end
My routes:
resources :adverts
Create.html.erb
<%= form_for #car, :url => adverts_path do |f| %>
<div><%= f.label :name %><br />
<%= f.text_field :name %></div>
<%= hidden_field_tag :model_id, params[:model_id] %>
<%= select_tag :engine_id, options_from_collection_for_select(#engines, "id", "name",:selected=>#car.engine_id) %>
<div><%= f.submit "Create car!" %></div>
<% end %>
I can create advert, but I can't to update it.
edit.html.erb
<%= form_for #car, :url => adverts_path do |f| %>
<div><%= f.label :name %><br />
<%= f.text_field :name %></div>
<%= hidden_field_tag :model_id, params[:model_id] %>
<%= select_tag :engine_id, options_from_collection_for_select(#engines, "id", "name",:selected=>#car.engine_id) %>
<div><%= f.submit "Update car!" %></div>
<% end %>
when I submited my form, I have an error - No route matches [PUT] "/adverts"
$ rake routes:
adverts GET /adverts(.:format) adverts#index
POST /adverts(.:format) adverts#create
new_advert GET /adverts/new(.:format) adverts#new
edit_advert GET /adverts/:id/edit(.:format) adverts#edit
advert GET /adverts/:id(.:format) adverts#show
PUT /adverts/:id(.:format) adverts#update
DELETE /adverts/:id(.:format) adverts#destroy
I need help.
When you are updating you have to let Rails know which object you want to update by passing an id.
In edit.html.erb change:
<%= form_for #car, :url => adverts_path do |f| %>
to:
<%= form_for #car, :url => advert_path(#car) do |f| %>
By the way, I find your code very strange. Why don't your model names match your controllers and routes? I mean you are creating an advert but your model is called car. That doesn't make any sense. Either call it car or advert, but don't mix them.
If you used RESTful routing, you don't need to specify a url, just need:
<%= form_for #car do |f| %>
The form can know #car is new record, or saved record, so it will send appropriate http method.
And in your update action:
def update
#car = Car.find(params[:id])
if #car.update_attributes(params[:car])
redirect_to root_path
end
end
I got myself in a similar situation today with a mismatched resource and model name. I agree the model and controller names need to correlate, but you can override the routes name to be whatever you want.
resources :cars, path: "adverts"
Along with RESTful routing
<%= form_for #car do |f| %>
You may also want to make sure your url: path is singular on the #form_form.

Passing Rails Parameters into Form

I'm trying to pass in two variables for a Nested Model form to use, but I'm getting an error. It's probably an easy syntax error that someone experienced could see right away, but I don't see it.
I have a template showing users, if you click one, it should take the user_id and community _id for use in the form. Both community and user are properly declared in the controller.
link to form:
<%= link_to "award badge", award_badge_badges_path, :user_id => user.id, :community_id => #community.id %>
The form uses two models - badge and badge winners. The user_id and community_id are needed for badge_winners which is nested in badges. The error I'm getting is "undefined local variable or method 'user_id' for #<#<Class:0x77544c0>:0x7714230>" so I think that something is wrong with the 2nd and 3rd lines in the form. Here's the form:
<%= form_for(#badge) do |f| %>
<%= f.hidden_field :user_id ,:value => user_id %>
<%= f.hidden_field :community_id ,:value => community_id %>
<%= f.label :Description %>
<%= f.text_area :description %>
<%= f.fields_for :badge_winners do |builder| %>
<%= render "badge_winner", :f => builder, :locals => {:user_id => user_id, :community_id => community_id} %>
<% end %>
<%= f.submit "Give Badge" %>
<% end %>
the show template in the controller:
def award_badge
#badge = Badge.new
badge_winners = #badge.badge_winners.build
end
the badge winner partial
<%= f.hidden_field :user_id ,:value => user_id %>
<%= f.hidden_field :community_id ,:value => community_id %>

Rails - Using form_for and fields_for, how do you access the sub-object while in the fields_for block?

In my first rails app I'm trying to use form_for and fields_for to create a nested object form. So far so good, but I can't figure out how to access the sub-object while in the fields_for block. I've pre-populated a field in the sub-object with data that I want to show in the user instructions.
Models
Garage:
has_many :cars, :dependent => :destroy
accepts_nested_attributes_for :cars
Car:
belongs_to :garage
Garage Controller
def new
#garage = Garage.new
for i in 1..5
#garage.cars.build :stall_number => i
end
end
_form.html.erb
<%= form_for #garage do |f| %>
<%= f.label :title, "Garage Name" %><br />
<%= f.text_field :title %>
<% f.fields_for :cars do |builder| %>
<p>Enter license for car parked in stall: <%= car.stall_number %></p>
<%= f.label :license, "License #:" %><br />
<%= f.text_field :license %>
<%= end %>
<%= end %>
As you can see, inside the builder block for :cars, I want to show, in my user instructions, the field: car.stall_number (populated in my controller with an integer):
<p>Enter license for car parked in stall: <%= car.stall_number%></p>
I've tried a many different ideas: #car.stall_number, object.car.stall_number, etc. No joy. Multiple searches and a look at the fields_for source code haven't helped my understanding. I would appreciate any guidance.
Update: For clarification, per Dan's suggestion I have tried builder.stall_number but it results in a
NoMethodError: undefined method 'stall_number' for #<ActionView::Helpers::FormBuilder:0x00000102a1baf0>
I just dealt with this today myself.
You can access the object of the fields_for through:
builder.object
where builder is your fields_for form builder object. In your particular case, you can say:
<p>Enter license for car parked in stall: <%= builder.object.stall_number%></p>
That should do it for you!
The way you are trying is does not work because you want to access car without filling that variable for data.
I guess you want to have multiple blocks of stalls, where you can enter license plates. For each stall you will need your own fields_for.
I would suggest something like that:
<%= form_for #garage do |f| %>
<%= f.label :title, "Garage Name" %><br />
<%= f.text_field :title %>
<% for i in 1..5 %>
<% f.fields_for #garage.cars[i] do |builder| %>
<p>Enter license for car parked in stall: <%= builder.stall_number%></p>
<%= builder.label :license, "License #:" %><br />
<%= builder.text_field :license %>
<% end %>
<% end %>
<% end %>
Within the fields_for you need to use the form object you define there, in this case builder. Since the data there are not mapped to the outer form (f), but to the cars object (builder).

How do you pass rails 3 forms params into an array?

I have a nested form (using accepts_nested_attributes_for in respective models):
<%= form_for(:technician, :url => {:controller => 'pos', :action => 'create_ticket'}) do |f| %>
<%= f.fields_for :service do |s| %>
<%= s.text_field :name %>
<%= s.text_field :name %>
<%= s.text_field :name %>
<%= s.text_field :name %>
<% end %>
<% end %>
This works fine if I only have one s.text_field. But once I add additional text_fields, it doesn't run properly. If you look at the source code, the id and name are the same for all six?
How do I put these params into an array? [so that I can isolate them like this:]
service1 = Service.named(params[:technician][:service][1][:name])
(I've tried the method described on railscasts episode 192, but it didn't work either).
After hours of trial and error, I've hacked something that works (but please let me know if you know a better, more eloquent way):
in view:
<%= form_for(:technician, :url => {:controller => 'pos', :action => 'create_ticket'}) do |f| %>
<% for #i in 1..6 do %>
<%= f.fields_for "services[#{#i}]" do |s| %>
<% end %>
<% end %>
<% end %>
in controller:
for i in 1..6 do
#service = Service.named(params[:technician][:services][i.to_s][:name]).first
end
make sure you turn i into string