Question

I've got Package belongs_to Shop. In my app, user can create package for their shop. I've got the 'create package' to work but it seems there's an error on redirect if I tried to save without inputting anything.

# package.rb
belongs_to :shop
validates_presence_of :name, :price, :description

# controller
def new
  @shop = current_user.shop
  @package = Package.new
end

def create
  @package = current_user.shop.packages.build(params[:package])
  @package.currency = current_user.shop.currency
  if @package.save
    flash[:success] = 'Package added.'
    redirect_to shop_path(current_user.shop)
  else
    render 'new'
  end
end

# routes.rb
resources :shops, except: [:destroy] do
  resources :packages
end

# new.html.erb
<%= form_for [@shop, @package] do |f| %>

Here's the error:

NoMethodError in Packages#create
undefined method `packages_path' for #<#<Class:0x007fab67191580>:0x007fab634ad7b8>

Extracted source (around line #6):
5:
6:   <%= form_for [@shop, @package] do |f| %>

Any help?

Was it helpful?

Solution

This will be because @shop is nil. The path is polymorphic, meaning it will generate the method for the path from the two array values. If the first is nil, it will think it is just a package path.

form_for [@package.shop, @package] will fix it. Or, in routes, you can expose a route at the top level to handle create.

resources :packages, :only => :create

I'd go with the first choice so the url looks about the same as 'new' if there's an error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top