简体   繁体   中英

How can I display data from a related model in a Rails form

I have two models

class Car
    has_many :engines                         
end

class Engine
    belongs_to :car
end

In the car form I have a select field where the user can select the engine type. The list might be "1.4L; 1.6L; 2.0L..."

Lets say I want to display additional information from the Engine model when the user selects a engine. This should be displayed on the Car form. This might be eg BHP, max revs, ...etc

How do I set something like this up. I guess there are two aspects:

  1. How to display data from the engine model on the car form without using a field (this data is not editable).

  2. How to update this data dynamically when the user selects an option in the select field.

Can anyone point me towards a starting point for this. I'm a bit lost where to begin.

Many thanks!

If you're working with collection_select in your form, you are setting two arguments, like:id and:name in your collection_select call. :id is the method called to determine the value for the option tag and:name is the method used to display the option tag's content.

Solution: Create a method (eg :name_for_select) in your engine model which returns a string with more information about your engine and call collection_select with:id, :name_for_select instead.

This is called a nested form, and if you google that you will find a lot of hints and tips. Eg check out this and this tutorial.

You should also consider using a form builder like formtastic or simple_form : they have a lot of helpers to make life easier for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM