Nested resources Stores in Users

Hey all,

I am trying to create a basic user and stores setup whereby stores are nested within users in my routes file as a resource. I have managed to create working forms for to create a new store but the issue I am having is that it’s not actually saving anything into my stores table.

I currenltly have the following view (stores#new)

<%= form_for [@user, @store] do |f| %>

	<div class = "field">
		<%= f.label :name %>
		<%= f.text_field :name %>
	</div>
	
	<%= f.submit "Submit" %>

<% end %>

My routes file is setup as follows:

MadeByV3::Application.routes.draw do

  match "signup" => "users#new"
  match "home" => "users#show"
  match "update" => "users#edit"

  match "stores" => "stores#index"
  match "store" => "stores#show"
  match "newstore" => "stores#new"
  match "updatestore" => "stores#edit"

  resources :users do
    resources :stores
  end

  get "login" => "sessions#new"
  post "login" => "sessions#create"
  delete "logout" => "sessions#destroy"
  get "logout" => "sessions#destroy"

  resources :sessions

  root :to => 'sessions#new'

end

and I have the following in my Stores controller



def new
    @store = Store.new
end

def create
    @user = current_user
    @store = @user.stores.build(params[:stores])

    if @store.save
      redirect_to store_path
    else
      render newstore_path
    end
  end

I am really quite confused by this as a very similar setup has definitely worked in the past.

Any advice people can offer on this really would be much appreciated :slight_smile:

Tom

Hi Tom,

Try this code change moving the build, http://guides.rubyonrails.org/getting_started.html


<%= form_for [@user, [B]@user.stores.build[/B]] do |f| %>


def create 
    @user = current_user
    @store = @user.stores.[B]new[/B](params[:stores])
    
    if @store.save
      redirect_to store_path
    else
      render newstore_path
    end
  end

The other thing it could be is that you need to define the relationships on the two models.