【问题标题】:Rails render contact form in other controllerRails 在其他控制器中呈现联系表单
【发布时间】:2013-02-18 20:24:53
【问题描述】:

我有两个控制器页面和联系人。页面显示来自数据库的内容。联系是简单的联系表格,效果很好。现在我想将此联系表放在特定页面中。但我尝试渲染它,但仍然出现没有模型类等错误。

这是我的联系人控制器(controllers/contact_controller):

class ContactController < ApplicationController

  def new
      @message = Message.new
    end

  def create
      @message = Message.new(params[:message])

      if @message.valid?
        NotificationMailer.new_message(@message).deliver
        redirect_to(root_path, :notice => "Sent.")
      else
        flash.now.alert = "Alert."
        render :new
      end
  end

end

这是我的消息模型(models/message.rb):

class Message

  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  attr_accessor :name, :email, :subject, :body

  validates :name, :email, :subject, :body, :presence => true
  validates :email, :format => { :with => %r{.+@.+\..+} }, :allow_blank => true

  def initialize(attributes = {})
    attributes.each do |name, value|
      send("#{name}=", value)
    end
  end

  def persisted?
    false
  end

end

这是表单(views/contact/new.html.erb):

<%= form_for @message, :url => contact_path do |form| %>
  <fieldset class="fields">
    <div class="field">
      <%= form.label :name %>
      <%= form.text_field :name %>
    </div>

    <div class="field">
      <%= form.label :email %>
      <%= form.text_field :email %>
    </div>
    <div class="field">
      <%= form.label :subject %>
      <%= form.text_field :subject %>
    </div>

    <div class="field">
      <%= form.label :body %>
      <%= form.text_area :body %>
    </div>
  </fieldset>

  <fieldset class="actions">
    <%= form.submit "Send" %>
  </fieldset>
<% end %>

如何将此表单放入页面视图???

【问题讨论】:

    标签: ruby-on-rails-3 render contact-form


    【解决方案1】:

    我认为你应该使用部分。例如,您可以将表单放在名为“app/views/shared/_message_form.html.erb”的文件中,然后放在contact/new(和所有其他页面)中,而不是将表单放在contact/new中: render 'shared/message_form'

    显然,您必须在每个控制器中设置@message,以便视图呈现此部分。也许您可以在 ApplicationController 中拥有一个方法,例如 set_message,并在需要时调用它。
    简单示例:

    class ApplicationController < ActionController::Base
      protect_from_forgery
    
      def set_message
        @message = Message.new params[:message] || {}
      end
    end
    

    然后你可以在任何控制器中使用set_message :)

    【讨论】:

    • 但是如何处理 :url => contact_path?我应该离开吗?
    • 以及如何做到这一点 set_message :)
    • 对于 url,我认为您希望请求始终转到联系人控制器,所以是的,您可以离开 contact_path。对于 set_message,我已经更新了答案。
    • 获得未定义的方法model_name' for NilClass:Class but when i set the set_message as helper_method in application controller and put there whole code from contact_controller create then the form is showing up on pages but dont 工作
    • 您是否在 PagesController 和 ContactController 中调用了set_message?更新他们所知道的控制器,并将您的页面视图发布到您想要使用表单的位置:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多