how to model an association with scaffold generator rails 4.2 -
basic example: 1) create new rails project following instruction:
rails new tut3
2) generate first scaffold model costumer
rails generate scaffold costumer name:string
3) generate second scaffold model product
rails generate scaffold product item:string costumer_id:integer
4) run migration (rake db:migrate) , after starting server (rails s) , adding few costumers (e.g. mario, anna etc..) go products page , expected costumer field dropdown table showing ids of costumers i've added see can insert in id number wish. why so? should costumer field of model product restricted costumer ids create in costumer page? , how can associate product costumer field costumer's name have created? hope question clear...))
rails generate scaffold
lot of job you, can't each , you.
you have manually set other things yourself. starting routes, have set them use customers/1/products
or customers/2/products
. scaffold
won't set these routes you.
resources :customers resources :products end
when mentioned customer_id
while generating scaffold
products, means product belongs_to
customer, , can check in code @ app/models/product.rb
. question is, how relation goes customer product. can customer have many products, or customer can have 1 product?
in app/models/customer.rb
,
class customer < activerecord::base has_one :product # having product per customer # has_many: products # note 's' @ end, makes customer have many products possible. end
similarly, need change view controller both fields, , whole lot of process. recommend go through basics of rails, how controllers , view work. after that, stuff pretty easy you.
Comments
Post a Comment