我在rails中有这个表单,在我看来是new.html.erb
<%= form_for( @rent , html: { class: 'form-horizontal' }) do |f| %>
<div class="form-group">
<label for="" class="col-lg-2 col-md-3 col-sm-3 col-xs-3 control-label">year:</label>
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
<%= f.text_field :year, class: 'form-control' %>
</div>
<div class="col-lg-2 col-md-3 col-sm-3 col-xs-3">
<%= f.submit 'Buscar', :class =>"btn btn-sm btn-info btn-flat" %>
</div>
<div class="clearfix"></div>
</div>
<% end %>
<%= render 'shared/error_messages', object: @rent %>
在我的控制器中我有这个
class RentsController < ApplicationController
def new
@rent = RentSearch.new
end
private
def search_params
params.require(:year).permit(:year)
end
end
在我的模型中,有这段代码:
class RentSearch
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
attr_accessor :year
validates :year, presence: true
validates :year, length: { is: 4 }
end
使用此代码我收到此错误
未定义的方法`坚持?&#39;对于#
但是我做了一些修改而没有显示错误,但是当提交没有显示任何错误和表格是空的时,我不知道如何解决这个问题。
在没有模型访问数据库并将所有验证传递给控制器并验证的情况下,在rails中创建表单的最佳方法是什么。
答案 0 :(得分:0)
我的解决方案
感谢@Зелёный寻求帮助。
route.rb
resources :rents, only: [:index, :new, :create]
rent.rb - model
class Rent
# Validations
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
attr_accessor :year
validates :year, presence: true
validates :year, length: { is: 4 }
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
end
def persisted?
false # which means this object persisted in the database.
end
end
rents_controller.rb
class RentsController < ApplicationController
def index
@params = params
end
def new
@rent = Rent.new
end
def create
@rent = Rent.new( params['/rents'] )
if @rent.valid?
redirect_to tg_rents_path( year: params['/rents']['year'] )
else
render :action => 'new'
end
end
end
new.html.erb
<%= form_for( tg_rents_path , url: {action: "create"}, html: { class: 'form-horizontal' }) do |f| %>
<div class="form-group">
<label for="" class="col-lg-2 col-md-3 col-sm-3 col-xs-3 control-label">year:</label>
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-3">
<%= f.text_field :year, class: 'form-control' %>
</div>
<div class="col-lg-2 col-md-3 col-sm-3 col-xs-3">
<%= f.submit 'Search', :class =>"btn btn-sm btn-info btn-flat" %>
</div>
<div class="clearfix"></div>
</div>
<% end %>
<%= render 'shared/error_messages', object: @rent %>
感谢所有!!