[英]Ruby on Rails - Render partial from another controller
我是Rails的新手,我環顧四周,發現這里的所有解決方案似乎都不起作用。 我覺得我缺少一些關鍵的東西。
我正在嘗試將/views/names/_form.html.erb中的部分內容渲染為具有不同控制器/views/posts/index.html.erb的另一個文件。 我不斷收到以下錯誤。
app / views / names / _form.html.erb,其中第一行出現:
格式中的第一個參數不能包含nil或為空提取的源(在第1行附近):
<%= form_for(@name)做| f | %> <%,如果@ name.errors.any? %>
<%= pluralize(@ name.errors.count,“錯誤”)%>禁止保存此>名稱:
我的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
我的帖子控制器如下:
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中呈現部分內容時,您的表單會嘗試找到@name對象,而該對象在post / index方法中找不到。 因此,我們需要使用新的Name對象初始化@name 。
def index
@posts = Post.all
@name = Name.new
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.