Skip to main content
Ask A Question
Notifications
You’re not receiving notifications from this thread.
Subscribe

How do I populate form control with data from database ? the RoR way..

Rails • Asked by Nahwin Rajan

Hi there,

this is very basic thing but How do I populate controls in my form with data from database ?

For example let say I want to create a Invoice / Order of items from my product list.
I must enable user to search the product from a dropdown. how do I populate these dropdown with my product list ?

I know that I can query all the the product and put it in a class variable which will be used in the view with ERB to populate the dropdown, but this might be okay when you have small set of product list or just a couple of dropdown. If I'm to use ajax which how to connect the request from the specific control to rails so it returns the data appropriate with each control (e.g: product list instead of supplier list) ?

I hope I make my question clear.


I'm not sure if this is the official "Rails" way, but the way I did this in a recent project was to create an array:

@products_array = []
@products.each do |product|
            @products_array << product.title
    end

And then to use this array as the collection in my simple form:

<%= b.input :product, collection: @products_array %>

As I said, there might be a Railsier way to do this, but this worked in my case. Hope it helps!


Hi Liz,

thanks for responding...

With your solution there's might be a performance issue when the products is in thousands of records..

Is it possible that this is where the front-end framework come to play and close the missing link ?


I would suggest using something like "Chosen" and populating it using Rails.

https://harvesthq.github.io/chosen/ - simple jQuery plugin which may be useful.

Populate similar to this...

<%= f.collection_select :product, @products.all, :id, :name, { class: 'chosen-select'} %>

I have used this a couple of times now and it works great, plus users can search for items. But it also depends on how you layout your form, remember to make sure its user friendly and you're not overdoing the form.


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 29,763+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.