Ask A Question

Notifications

You’re not receiving notifications from this thread.

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

Nahwin Rajan asked in Rails

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.

Reply

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!

Reply

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 ?

Reply

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.

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 85,972+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.