简体   繁体   English

其他控制器中的实例变量-Rails

[英]Instance variable in other controller - Rails

I have a mostly static website built with Rails. 我有一个使用Rails构建的静态网站。 Each page is managed by a pages controller. 每个页面由页面控制器管理。 I have a contact form at the bottom of each page. 每页底部都有一个联系表格。 I am using mail_form. 我正在使用mail_form。 Each form requires a new ContactForm object. 每个表单都需要一个新的ContactForm对象。 I have defined contact form. 我已经定义了联系表格。 This is it's schema: 这是它的模式:

ActiveRecord::Schema.define(version: 20170130205713) do

create_table "contact_forms", force: :cascade do |t|
  t.string   "name"
  t.string   "email"
  t.string   "message"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
end

end

Here is the controller: 这是控制器:

class ContactFormsController < ApplicationController
def new
  @contact_form = ContactForm.new
end

def create
  begin
    @contact_form = ContactForm.new(params[:contact_form])
    @contact_form.request = request
    if @contact_form.deliver
      flash.now[:notice] = 'Thank you for your message!'
    else
      render :new
    end
  rescue ScriptError
    flash[:error] = 'Sorry, this message appears to be spam and was not delivered.'
  end
end
end

I would like to be able to create a new instance of the ContactForm object in each of the page controller's views. 我希望能够在每个页面控制器的视图中创建ContactForm对象的新实例。 When I attempt to define 当我尝试定义

@contact_form = ContactForm.new

in the home view of the pages controller, for example, I get this error: 例如,在页面控制器的主视图中,出现以下错误:

NoMethodError in PagesController#home
undefined method `type' for {:validate=>true}:Hash

Is there a way to do this without moving all of my actions into the ContactForm controller? 有没有一种方法可以将我的所有动作都移到ContactForm控制器中?

If I am getting you correctly, you need to have an instance variable of contact_form that could be used in every page as every page has contact form in its bottom. 如果我正确地了解了您,则需要有一个contact_form实例变量,该变量可以在每个页面中使用,因为每个页面的底部都有联系表单。

You could create a private method in ApplicationController and use that as 'before_action' in whatever controller, whose action you need that object to be present. 您可以在ApplicationController中创建一个私有方法,并将其用作任何控制器中的“ before_action”,您需要执行该操作的对象。 Something like below 像下面这样

Add below line in ApplicationController.rb 在ApplicationController.rb中添加以下行

private
def init_contact_form
  @contact_form ||= ContactForm.new
end 

And use below in Controller where you need that @contact_form object. 并在Controller中使用以下需要@contact_form对象的位置。 Add below in your PagesController.rb 在您的PagesController.rb中添加以下内容

before_action :init_contact_form

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM