我正在创建一个登录页面,我的根页面上有两个表单(尝试创建登录页面)。对轨道上的红宝石很新,请原谅我,因为我要解释这个非常糟糕。
着陆页控制器(landing_controller)如下所示:
class LandingController < ApplicationController
def index
@email = Email.new
@design = Design.new
end
end
emails_controller(emails_controller)如下所示:
class EmailsController < ApplicationController
protect_from_forgery with: :exception
def new
@email = Email.new
end
def create
@email = Email.new(params[email_params])
respond_to do |format|
if @email.save
format.html { redirect_to(root_path, :notice => 'Thank You For Subscribing!') }
format.json { render json: Email.create(email_params) }
else
format.html { redirect_to(root_path)}
format.json { render :json => @email.errors, :status => :unprocessable_entity }
end
end
end
private
def email_params
params.require(:email).permit(:username, :email)
end
end
和设计控制器(designs_controller)看起来与emails_controller几乎相同。
然后我在email.rb模型中进行了一些验证:
class Email < ActiveRecord::Base
validates :username, :presence => true
validates :email, :presence => true
end
再次,design.rb看起来几乎一样。
我在着陆页(root_path)索引上的表单如下所示:
<%= form_for @email, url: emails_path, html: {class: "email-form"} do |f| %>
<% if @email.errors.any? %>
<h3>Error</h3>
<ul>
<% @email.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
<% end %>
<h2>Receive Notifications</h2>
<%= f.text_field :username, :class => 'email-box', :placeholder => "First Name", :autocomplete => :off %>
<%= f.text_field :email , :class => 'email-box', :placeholder => "Email", :autocomplete => :off %>
<%= f.submit "Subscribe", :class => 'email-submit' %>
<p class="info">- We'll update you when we launch our new website</p>
<% end %>
当我提交表格中断验证时,我没有错误,如果我按照验证规则提交表单,我不知道它是否在数据库中创建了新条目。如果有人可以提供帮助,我会非常感激。
答案 0 :(得分:2)
您需要渲染着陆控制器索引操作,而不是重定向到它。因为在重定向时,它会执行@email = Email.new,并且电子邮件中的所有错误都消失了。尝试将其作为电子邮件控制器中的创建操作
def create
@email = Email.new(email_params)
respond_to do |format|
if @email.save
format.html { redirect_to root_path, notice: 'Thank You For Subscribing!' }
format.json { render json: Email.create(email_params) }
else
@design = Design.new
format.html { render "landing/index" }
format.json { render :json => @email.errors, :status => :unprocessable_entity }
end
end
end
有关成功或错误消息,请将其放入application.html.erb
<% if flash[:error].present? %>
<p class='flash-error'><%= flash[:error] %></p>
<% end %>
<% if flash[:notice].present? %>
<p class='flash-notice'><%= flash[:notice] %></p>
<% end %>