Topic: Problem with saving nested resource stores

Hey all,

I have setup a nested resource in my routes of Stores under users in the usual way and made associations in both models has_many :stores and belongs_to :user etc.

What I am struggling with is that I can't get my stores to actually save into the stores table in my database. I am receiving no errors and as such am very confused as to what's happening.

I currently have this in my 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 controller create and new actions look like this:

 def new
    @store = Store.new
  end

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

I have also pushed all my code to github here https://github.com/supert56/Made_by_v2

Any help people can offer really would be appreciated as I have been struggling to get this working for a few days now.

Many thanks in advance!

Tom smile

Re: Problem with saving nested resource stores

You have no @user variable in your controller 'new' action, just a @store object. Try to add it as follows:

def new
  @user = current_user
  @store = @user.stores.build
end

Re: Problem with saving nested resource stores

Hey,

Thanks so much for your reply this seems to have worked and it is actually writing to the table now with the users Id.

Only thing not happening is it isn't passing the store 'name' to the table - do you have any idea why this might be?

Alternatively do you have a working example of a nested resource I can see to try and apply it to my own code.

Sorry for the amateur question, I am quite new to this smile

Re: Problem with saving nested resource stores

See episodes 196,197 on Rails cats on nested forms.