将Rails表单部分嵌入到另一个页面中
我正在构建一个带有联系我们页面的rails 4.2.0应用程序(此页面确实有一个半空控制器)。 我试图从另一个控制器嵌入一个表单部分。
这是代码(减去文本):
当我运行这个时,我得到错误’forms中的第一个参数不能包含nil或为空’。
我的查询表格看起来像一个基本的铁轨forms:
prohibited this enquiry from being saved:
可能是错误的原因是什么? 或者是否有更好的方法将视图嵌入另一个视图?
更新/编辑:
这是路线:
devise_for :users resources :rooms do resources :viewings end resources :rmcats resources :extras resources :extracats resources :enquiries root :to => redirect('/pages/home') get 'pages/home' get 'pages/contactus'
和查询控制器:
class EnquiriesController < ApplicationController before_action :set_enquiry, only: [:show, :edit, :update, :destroy] # GET /enquiries def index @enquiries = Enquiry.all end # GET /enquiries/1 def show end # GET /enquiries/new def new @enquiry = Enquiry.new end # GET /enquiries/1/edit def edit end # POST /enquiries def create @enquiry = Enquiry.new(enquiry_params) if @enquiry.save redirect_to @enquiry, notice: 'Enquiry was successfully created.' else render :new end end # PATCH/PUT /enquiries/1 def update if @enquiry.update(enquiry_params) redirect_to @enquiry, notice: 'Enquiry was successfully updated.' else render :edit end end # DELETE /enquiries/1 def destroy @enquiry.destroy redirect_to enquiries_url, notice: 'Enquiry was successfully destroyed.' end private # Use callbacks to share common setup or constraints between actions. def set_enquiry @enquiry = Enquiry.find(params[:id]) end # Only allow a trusted parameter "white list" through. def enquiry_params params.require(:enquiry).permit(:subject, :e_description) end end
这是页面控制器:
class PagesController For pages this will rarely be needed as it should 404. def resource_not_found yield rescue ActiveRecord::RecordNotFound redirect_to root_url, :notice => "Page not found." end end
编辑:
日志:
Started GET "/pages/contactus" for ::1 at 2015-03-21 01:05:25 +0000 Processing by EnquiriesController#new as HTML [1m[35mUser Load (0.0ms)[0m SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]] Rendered enquiries/_form.html.erb (0.0ms) Rendered pages/contactus.html.erb within layouts/application (0.0ms) Completed 200 OK in 235ms (Views: 234.6ms | ActiveRecord: 0.0ms)
它告诉你@enquiry
在尝试渲染表单时是零。 您需要调用new
操作来创建表单所代表的@enqiury
。
您可以将路线更改为:
get 'pages/contactus' => 'enquiries#new'
然后在您的查询控制器中:
def new @enquiry = Enquiry.new render 'pages/contactus' end
编辑:
好的,现在我们将Friends Systems的答案结合起来:
<% if user_signed_in? %> <%= render 'enquiries/form' enquiry: @enquiry %> <% end %>
现在将@enquiry
中的任何@enquiry
实例更改为enquiry
这是因为您需要将变量传递给partial。
问题是,你的@enquiry变量没有在渲染部分的上下文中定义。 它不是由被调用的控制器动作定义的,你应该通过调用创建一个查询实例
@enquiry = Enquiry.new
在你的行动中。
此外
在其他地方使用它我会将@enquiry实例变量作为locale变量传递给partial
<% render 'enquiries/form', :enquiry => @enquiry %>
你的表单方法应如下所示:
<%= form_for enquiry do |f| %> ... <% end %>
当然,所有的实例变量都应该被替换。 只需删除’@’
编辑:根据您在上面发布的控制器设置,最好的方法是使用类似的东西
@enquiry ||= Enquiry.new
如果@enquiry为零,则在您的表单中使用shure创建一个新实例。