lundi 2 novembre 2015

Ruby on Rails - Render partial from another controller

I'm new to rails and I've looked around and none of the solutions on here I've found seem to work. I feel that I am missing something crucial.

I am trying to render a partial from /views/names/_form.html.erb into another file with a different controller /views/posts/index.html.erb. I keep getting the following error.

app/views/names/_form.html.erb where line #1 raised:

First argument in form cannot contain nil or be empty Extracted source (around line #1):

<%= form_for(@name) do |f| %> <% if @name.errors.any? %>

<%= pluralize(@name.errors.count, "error") %> prohibited this >name from being saved:

My HTML code is as follows:

<div class="modal" id="myModal">
<h1>Company Name</h1>
<div class="modal-body">

<%= render :partial => '/names/form' %>

...etc...

My Names controller is as follows:

 class NamesController < ApplicationController

 before_action :set_name, only: [:show, :edit, :update, :destroy]

 def index
 @names = Name.all
 end


 def show
 end


 def new
 @name = Name.new
 end

 def edit
 end


 def create
 @name = Name.new(name_params)
  respond_to do |format|
  if @name.save
    format.html {  rredirect_to @name, notice: 'Post created'  }
    format.json { render :show, status: :created, location: @name }
  else
    format.html { render :new }
    format.json { render json: @name.errors, status:  :unprocessable_entity }

  end

   end

   end

My Posts controller is as follows:

 class PostsController < ApplicationController
      before_action :set_post, only: [:show, :edit, :update, :destroy]
      before_action :authenticate_user!, except: [:index]
     # before_filter :first_time_visiting?

      # GET /posts
      # GET /posts.json
      def index
        @posts = Post.all
      end

      # GET /posts/1
      # GET /posts/1.json
      def show

        @posts = Post.all

      end

      # GET /posts/new
      def new
        @post = current_user.posts.build
      end

      # GET /posts/1/edit
      def edit
      end

      # POST /posts
      # POST /posts.json
      def create
        @post = current_user.posts.build(post_params)

        respond_to do |format|
          if @post.save
            format.html { redirect_to @post, notice: 'Post was successfully created.' }
            format.json { render :show, status: :created, location: @post }
          else
            format.html { render :new }
            format.json { render json: @post.errors, status: :unprocessable_entity }
          end
        end
      end

And finally this is my routes file

Rails.application.routes.draw do
    resources :posts
    devise_for :users
    resources :names


     root 'index#home'

      get "about" => 'index#about'

      get "contact" => 'index#contact'

      get 'closings' => 'index#closings'

      get 'signin' => 'users#sign_in'

Thank you so much for your help.

Aucun commentaire:

Enregistrer un commentaire