【问题标题】:Ruby on Rails - Render partial from another controllerRuby on Rails - 从另一个控制器渲染部分
【发布时间】:2016-02-03 03:22:58
【问题描述】:

我是 Rails 新手,我环顾四周,发现这里的解决方案似乎都不起作用。我觉得我错过了一些重要的东西。

我正在尝试将 /views/names/_form.html.erb 中的部分内容渲染到具有不同控制器 /views/posts/index.html.erb 的另一个文件中。我不断收到以下错误。

app/views/names/_form.html.erb 其中第 1 行提出:

表单中的第一个参数不能包含 nil 或为空 提取的源代码(第 1 行附近):

禁止保存此>name:

我的HTML代码如下:

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

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

...etc...

我的名字控制器如下:

 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

我的 Posts 控制器如下:

 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

最后这是我的路线文件

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'

非常感谢您的帮助。

【问题讨论】:

  • 对不起,澄清html代码是为views/posts/index.html.erb

标签: html ruby-on-rails ruby ruby-on-rails-3


【解决方案1】:

在您的 post/index 方法中添加以下行。何时在您的视图 html 中呈现部分内容时,您的表单会尝试查找在 post/index 方法中找不到的 @name 对象。所以我们需要用新的 Name 对象初始化 @name

def index
  @posts = Post.all
  @name = Name.new
end

【讨论】:

    猜你喜欢
    • 2012-11-06
    • 2013-06-24
    • 2017-05-07
    • 1970-01-01
    • 2014-05-28
    • 2012-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多