Welcome to Working With Rails


Discussion Forums

Discuss all things Ruby on Rails with perhaps the web's most vibrant group of Ruby on Rails enthusiasts.
RoR - The correct approach with multiple tables
3 Posts
RoR - The correct approach with multiple tables

josiasbh Gregmolnar is correct about accepts_nested_attributes_for being one approach, but I think you should step back for a second and look at what you are doing. In your situation, I think the proper thing to do would be to use the model generator and not the scaffold generator.

rails generate scaffold city name:string state_id:integer


rails generate model city name:string state_id:integer

The difference is when you generate a scaffold you get the controller, the model(and database migrations) and the views. In your situation, the views and controller are not necessary. Also keep in mind that there is nothing that restricts you from creating one model from another controller. Having something like this will work.


def create
  @user = User.new params[:user]
      @address = Address.new params[:address]
      if @user.save && @address.save
        flash[:notice] = "It is saved"
        redirect_to root_url
        flash[:error] = "It did not save"
        render :new

Now that is just an example, because it is not actually very good code. One save might happen and one could fail and you would hit the else condition. Also, your form would need to send both user and address sets of params, but it is meant to show that nothing restricts you from limiting the address model to only the address controller.

How you design the view and controller action will largely depend on how your relationships between you 5 models are. i.e has_man or has_one. If you have any more questions submit a follow up and I can help some more.

If you want to manage multiple models on the same form you will need accept_nested_attributes_for. A good screencast about it: http://railscasts.com/episodes/196-nested-model-form-part-1

Forum Rating: 100
Sign In To Rate Post

Hi there!

I have 5 controllers and 5 views in my own project, I divided my app in these 5 main areas and I put many actions inside those areas/controllers.

I need many tables/models in my database, example: in the address content I need to separate some tables and build the correct relations to avoid duplicated fields... I want to manage address, user, person, legal entity, events, and many more.

What is the correct way to think in Rails at this point, if i create a model using scaffold:

rails generate scaffold city name:string state_id:integer

I get the correct model, the controller and views automatically.

I want to manage that City table in another controller, one of that five controllers that I created before, I need to manage many tables in just one view, or one controller.

If you know what I need to read and help me, I would appreciate.

Last Edited by josiasbh at 10 Feb 01:24
3 Posts
Login to add your message