Sandro Palmieri
Sandro Palmieri

Reputation: 1203

How to model an association with scaffold generator rails 4.2

Basic example:

  1. I create a new rails project with following instruction:

    rails new tut3
    
  2. I generate my first scaffold model customer

    rails generate scaffold customer name:string
    
  3. I generate my second scaffold model product

    rails generate scaffold product item:string customer_id:integer
    
  4. I run the migration (rake db:migrate) and after starting the server (rails s) and adding a few customers (e.g. Mario, Anna etc..) I go to the products page and I expected to get a customer column with a dropdown table showing the ids of the customers I've added but I see that I can insert in any id number I wish. Why so? Should the customer column of the model product just restricted to the customer IDs that I create in the customer page? And how can I associate the product customer column just with the customer's name that I have created?

Hope my question is clear...))

Upvotes: 1

Views: 1472

Answers (2)

khaled
khaled

Reputation: 11

Use

rails generate scaffold product item:string customer:belongs_to

Upvotes: 1

Arslan Ali
Arslan Ali

Reputation: 17802

rails generate scaffold does a lot of job for you, but it can't do each and everything for you.

You will have to do manually set other things for yourself. Starting with routes, you have to set them so that you could use something like customers/1/products or customers/2/products. scaffold won't set these routes for you.

resources :customers do
  resources :products
end

When you mentioned customer_id while generating scaffold for products, that means a product belongs_to a customer, and you can check it in the code at app/models/product.rb. But now the question is, how the relation goes from a customer to a product. Can a customer have many products, or a customer can have only one product?

In app/models/customer.rb,

class Customer < ActiveRecord::Base
  has_one :product # For having only product per customer
  # has_many: products # Note that 's' at the end, this makes a customer have as many as products as possible. 
end

Similarly, you need to change the view as well as the controller for both fields, and that is a whole lot of process. For that I recommend you to go through the basics of Rails, how do controllers and view work. After that, the stuff would be pretty much easy for you.

Upvotes: 0

Related Questions