1RailsBeginner1
1RailsBeginner1

Reputation: 11

Rails: Can't access parent id in controller create action

I have a Rails app that I've been working on. I have set up Users, Catalogues and Products.

Users have many Catalogues. Catalogues have many Products.

In the Products controller, I'm attempting to create a product. This is the function I currently have:

def create
  @product = @catalogue.products.build(params[:product])

  if @product.save
    flash[:success] = "Product created!"
    redirect_to @catalogue
  else
    flash[:error] = "Save error: Product not created."
    render 'static_pages/home'
  end
end

I have a function that sets the @catalogue using a before_filter:

  def get_catalogue 
    @catalogue = Catalogue.find_by_id(:catalogue_id)
  end

This function doesn't appear to be working as the error I'm getting is:

NoMethodError in ProductsController#create

undefined method `products' for nil:NilClass

I assumed that the products catalogue_id would be set after the new action was performed.

Thanks for any help in advance.

Upvotes: 1

Views: 710

Answers (2)

PaulJvR
PaulJvR

Reputation: 61

Why not use nested routing?

resources :catalogues do

resources :products

end

Then you can use

catalogue_products_path(@catalogue)

which will give access to params[:catalogue_id] to you in the controller.

Upvotes: 2

I think the problem is in the before_filter. I think it should use params[:catalogue_id] and not a symbol.

def get_catalogue 
  @catalogue = Catalogue.find_by_id(params[:catalogue_id])
end

Upvotes: 2

Related Questions