I am a Java developer I've been learning Rails for the past few days. I have a Java EE application (Uses Hibernate for ORM) that I am trying to port to Rails. I have used scaffolding to generate a few of my models. But I have other models which contain references to other models. How do I define the relations? Can I scaffold that as well?
Here is an example for what I am trying to do.
public class Engine {
private int valves;
private int capacity;
private int rpm;
}
I can scaffold the Engine class in ruby just by doing the following:
rails generate scaffold Engine valves:integer capacity:integer rpm:integer
Here is the tricky part for me:
public class Car {
private Engine engine;
}
How do I scaffold the Car class in Ruby?
If I understand correctly you are looking for associations. Here's a great guide that you should read. The thing to understand here is that you define in your models how the they relate to each other with a series of methods described in that guide.
Here is what I would suggest you do:
rails generate scaffold Car <db columns>
rails generate model Engine valves:integer capacity:integer rpm:integer car_id:integer
In your two models:
class Car < ActiveRecord::Base
has_one :engine
end
class Engine < ActiveRecord::Base
belongs_to :car
end
You can actually generate scaffold for both models...that will create controller and views. But in this case it might make sense to add
accepts_nested_attribues_for :engine
to your Car model instead. This will allow you to manage the manipulation of the Engine model from the controller and views of the Car model.
At any rate, I hope this helps you start to find what you need.