SitePoint Sponsor

User Tag List

Results 1 to 2 of 2

Hybrid View

  1. #1
    SitePoint Enthusiast
    Join Date
    Jun 2009
    Posts
    84
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    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)

    Code:
    <%= 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:

    Code:
    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

    Code:
    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

    Tom

  2. #2
    padawan silver trophybronze trophy markbrown4's Avatar
    Join Date
    Jul 2006
    Location
    Victoria, Australia
    Posts
    4,118
    Mentioned
    28 Post(s)
    Tagged
    2 Thread(s)
    Hi Tom,

    Try this code change moving the build, http://guides.rubyonrails.org/getting_started.html
    Code:
    <%= form_for [@user, @user.stores.build] do |f| %>
    Code:
    def create 
        @user = current_user
        @store = @user.stores.new(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.


Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •