Question

I have a software table, which has 4 fields; id, vendor, title and edition. I need a drop down box in my licenses form which will show every record like this: vendor - title - edition, but then only save the id of the chosen record to the database. I'm currently using a text box where the user can just enter the id of the software which will be saved to the database. here is my current form:

<%= form_for(@licenses) do |f| %>

<div class="well">
<%= f.label 'Software' %><br />
<%= f.text_field :software_id %>


<%= f.label 'Quantity' %><br />
<%= f.text_field :amount %>

<%= f.submit 'add'%>
</div>

<% end %>

I need to change the software text field into a drop down box, sorry if this is vague, i've not had anything to do with drop down boxes before.

Était-ce utile?

La solution

Checkout collection_select for populating drop box

create a method in softwarer model like

def title_edition
"#{self.vendor.name}- #{self.title} - #{edition}"
end
@softwares = Software.all #In controller

and in view

<%= f.collection_select :software_id ,@softwares,:id,:title_edition %>

Autres conseils

You would want collection_select with something like this:

f.collection_select(:software_id, Software.all, :id, :blah, :prompt => true) 

Now the :blah is the tricky thing. In your Software model you will need to define a method that returns the concatenated string you would like; I called it :blah to draw your attention to it but it can be named anything. It would look like this:

def blah
    "#{self.vendor}-#{self.title}-#{self.edition}"
end

That should return the string like you mentioned and when you call it in collection_select display it like you want it.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top