mercredi 8 mars 2017

Ruby on Rails: Creating a new children instance using the parent's id/Working with associated classes

One of my goal on this web app project is to make each tailor add or create products. So I made a MCV structure from scratch for the Tailor for the sign up page. And then I scaffold the Product since basic CRUD functions will be used by the Tailor to create a product. And then I put them into has_many/belongs_to relationship. I generated a migration which adds a column tailor_id into the Product class. Then I put these nested routes:

resources :tailors do
   resources :products
end 
resources :products #this is for debugging for whether a customer can see all the Products created by all the Tailors

then I ran rake routes and checked which path I can use to create a product with a given tailor_id then I decided to use the /tailors/:tailor_id/products/new. So I added a code which is a link in my tailor show page:

<%= link_to 'Add Product', new_tailor_product_path(@tailor.id) %>

and the I edited the new and create functions in the products_controller since the path is directed there) like this:

  def new
    @tailor = Tailor.find(params[:tailor_id])
    @product = @tailor.Product.new(params[@tailor])
  end

  def create
    @tailor = Tailor.find(params[:tailor_id])
    @product = @tailor.Product.new()
    @product.product_name = params[:product][:product_name]
    @product.product_description = params[:product][:product_description]
    @product.price = params[:product][:price]
    @product.tailor_id = params[:product][@tailor]
    @product.save
    redirect_to "/tailors/#{@tailor}"
  end

but the error says Undefined method 'Product' that occurs in the where the @product = @tailor.Product.new(params[@tailor])is

I don't really understand why is this an error because I'm pretty sure I called the class right (It's been taught to us that classes must begin with capital letter and is singular) and it's clear that I'm not calling a method.

Please explain the concept of calling the parent class and its data. Am I not allowed to call the Tailor class and its data inside the product_controller in this case? Is my approach wrong or am I in the right direction?

Also, other Remarks and Error corrections about the other parts of my codes are welcomed

Aucun commentaire:

Enregistrer un commentaire