Ruby on rails 当文本\字段\标记不是RubyonRails中模型的一部分时,如何验证它?
我正在创建一个婚礼rsvp应用程序,遇到了一个问题。我有一个带有一些字段的RSVP模型,然后在我的表单中,我添加了一个不属于RSVP模型的额外文本字段(Ruby on rails 当文本\字段\标记不是RubyonRails中模型的一部分时,如何验证它?,ruby-on-rails,Ruby On Rails,我正在创建一个婚礼rsvp应用程序,遇到了一个问题。我有一个带有一些字段的RSVP模型,然后在我的表单中,我添加了一个不属于RSVP模型的额外文本字段(text\u field\u tag),但是我想在我的RSVP.rb模型中验证它,使其成为必需的 额外字段是一个“代码”字段(如下所示),我将在婚礼请柬中提供该字段 我还想将控制器中输入的“代码”与创建rsvp时的有效静态代码进行“比较” new.html.erb <%= form_for(@rsvp, :html => { clas
text\u field\u tag
),但是我想在我的RSVP.rb
模型中验证它,使其成为必需的
额外字段是一个“代码”字段(如下所示),我将在婚礼请柬中提供该字段
我还想将控制器中输入的“代码”与创建rsvp时的有效静态代码进行“比较”
new.html.erb
<%= form_for(@rsvp, :html => { class: 'form-horizontal', role: 'form' }) do |r| %>
<div class="form-group">
<div class="control-label pull-left">
<%= r.label :party, 'Name' %> <span class="required">*</span>
</div>
<div class="control-label">
<%= r.text_field :party, class: 'form-control', placeholder: 'Individual or family name', autofocus: true %>
</div>
</div>
...
<div class="form-group">
<div class="control-label pull-left">
<label for="rsvp_code">Enter code found in invitation</label> <span class="required">*</span>
</div>
<div class="control-label">
<%= text_field_tag 'rsvp_code', nil, class: 'form-control' %>
</div>
</div>
...
<% end %>
def create
@rsvp = Rsvp.new(rsvp_params)
#compare the values of the text field to invitation code
#if values match then proceed
#else send error message
if @rsvp.save
flash[:success] = 'Thank you'
redirect_to root_path
else
render 'new'
end
end
class Rsvp < ActiveRecord::Base
validates text_field_tag presence: true #or something like this
end
rsvp.rb
<%= form_for(@rsvp, :html => { class: 'form-horizontal', role: 'form' }) do |r| %>
<div class="form-group">
<div class="control-label pull-left">
<%= r.label :party, 'Name' %> <span class="required">*</span>
</div>
<div class="control-label">
<%= r.text_field :party, class: 'form-control', placeholder: 'Individual or family name', autofocus: true %>
</div>
</div>
...
<div class="form-group">
<div class="control-label pull-left">
<label for="rsvp_code">Enter code found in invitation</label> <span class="required">*</span>
</div>
<div class="control-label">
<%= text_field_tag 'rsvp_code', nil, class: 'form-control' %>
</div>
</div>
...
<% end %>
def create
@rsvp = Rsvp.new(rsvp_params)
#compare the values of the text field to invitation code
#if values match then proceed
#else send error message
if @rsvp.save
flash[:success] = 'Thank you'
redirect_to root_path
else
render 'new'
end
end
class Rsvp < ActiveRecord::Base
validates text_field_tag presence: true #or something like this
end
类Rsvpdef create
if params["rsvp_code"] == "YOUR_CODE"
Rsvp.new(rsvp_params)
...
else
flash["error"] = 'Your invitation code does\'t match'
redirect_to rsvp_new_path
end
end
这里的其他答案将起作用。但是它们很乱。验证属于模型
class Rsvp < ActiveRecord::Base
attr_accessor :rsvp_code
validates :rsvp_code, presence: true
end
类Rsvp
更改为
阅读更多关于这太棒了,我喜欢这个。非常感谢。此外,我还在模型中添加了一个私有方法(
rsvp.rb
),以验证输入的代码是否与邀请中提供的代码相同!!