【问题标题】:RoR - Adding form over a static pageRoR - 在静态页面上添加表单
【发布时间】:2015-05-08 19:57:28
【问题描述】:

谁能告诉我如何在我的 Rails 应用程序中添加一个简单的表单?我在单独的页面上创建了一个表单,它工作正常,但如何在我的静态页面上实现它?

我的应用程序/views/contact/_form.html.haml

.container
  %h1 Contact
  = simple_form_for @contact, :html => {:class => 'form-horizontal' } do |f|
    = f.input :name, :required => true
    = f.input :email, :required => true
    = f.input :message, :as => :text, :required => false, :input_html => {:rows => 10}

    .hidden
      = f.input :nickname, :hint => 'Leave this field blank!'
    .form-actions
      = f.button :submit, 'Send message', :class=> "btn btn-primary"

我的联系人控制器:

    class ContactsController < ApplicationController

    def new
        @contact = Contact.new
    end

    def create
        @contact = Contact.new(params[:contact])
        @contact.request = request
        if @contact.deliver
            flash.now[:error] = nil
        else
            flash.now[:error] = 'Cannot send message.'
            render :new
        end
    end

end

我要在哪里添加表单,(index.html.haml)(静态页面)

#callouts2
.callout_inner
    .wrapper
        .callout
            =render 'contacts/form'

我的路线.rb

Rails.application.routes.draw do

  devise_for :users
  resources :posts do
    member do
      get "like", to: "posts#upvote"
      get "dislike", to: "posts#downvote"
    end
    resources :comments
  end

  authenticated :user do
    root 'posts#index', as: "authenticated_root"
  end

  resources "contacts", only: [:new, :create]

  root 'pages#index'

views/contact/create.html.haml 中还有另一个“感谢您的消息”页面,我也需要将它们重定向到该页面。

编辑:我在索引页中添加了一个=render 'contacts/form',但它给了我一个错误:

页面中的参数错误#index C:/Sites/blogger/app/views/contacts/_form.html.haml 其中第 3 行提出:

表单中的第一个参数不能包含 nil 或为空 Trace of 模板包含:app/views/pages/index.html.haml

【问题讨论】:

    标签: html ruby-on-rails forms static-pages


    【解决方案1】:

    如果您的表单名为“_form”,您可以执行以下操作:

    render "form"
    

    我不熟悉haml,不知道还需要什么其他语法,但那是您将表单添加到页面中的方式。

    【讨论】:

    • haml 的语法是 = render 'form' 我将它添加到我的索引页面,但它给了我一个 ArgumentError,即“表单中的第一个参数不能包含 nil 或为空”
    • 修复了!我在表单中添加了= simple_form_for(Contact.new) do |f|,它起作用了,尽管我知道这不是一个好习惯。但是您还有其他选择吗?
    • 不知道为什么这是一个不好的做法?你的意思是在haml?因为我只真正了解 ERB,所以 haml 会妨碍我。每个表单都需要知道它的用途,这就是您最初遇到错误的原因。如果您的意思是“Contact.new”,那么只需将其更改为您的实例变量。即= simple_form_for(@contact)...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-09
    • 1970-01-01
    • 1970-01-01
    • 2018-07-18
    • 2022-01-04
    • 1970-01-01
    • 2016-09-12
    相关资源
    最近更新 更多