尝试使用适用于 Kohana 3.2 的 ORM 进行验证。
目前我有我的模型:
<?php defined('SYSPATH') or die('No direct access allowed.');
class Model_Brand extends ORM {
protected $_has_many = array('models' => array());
protected $_rules = array(
'name' => array(
'not_empty' => NULL,
'min_length' => array(3),
'max_length' => array(20),
),
'sku' => array(
'not_empty' => NULL,
'min_length' => array(3),
'max_length' => array(6),
),
);
}
这是我的 Controller :
<?php defined('SYSPATH') or die('No direct script access.');
class Controller_Brand extends Controller_Layout {
public function action_view()
{
$brands = ORM::factory('brand')->find_all();
$this->template->title = __('Brands');
$this->template->content = View::factory('brands/view' );
$this->template->content->set('brands', $brands);
}
public function action_edit()
{
if($_POST)
{
try
{
$brand = ORM::factory('brand', $this->request->param('id'));
$brand->values($_POST);
if($brand->check())
{
$brand->update();
$brand->save();
//go to brand/views
}
}
catch (ORM_Validation_Exception $e)
{
//pass errors to brand/edit
}
}
else
{
$brand = ORM::factory('brand', $this->request->param('id'));
$this->template->title = __('Edit Brand');
$this->template->content = View::factory('brands/edit' );
$this->template->content->set('brand', $brand);
}
}
}
我什至还没有谈到错误部分。我遇到的问题是它对任何输入进行验证而不是使用模型中的规则。另外,如果有人能告诉我应该如何设计这样的更新操作,那将是一个很大的帮助。谢谢。
最佳答案
我就是这样做模型验证的,我觉得最直接也最优雅。
首先,我在 rules() 方法中设置我的规则:
<?php defined('SYSPATH') or die('No direct access allowed.');
class Model_Brand extends ORM {
public function rules()
{
return array(
'name' => array(
array('not_empty'),
array('min_length', array(':value', 3)),
array('max_length', array(':value', 20)),
)
'sku' => array(
array('not_empty'),
array('min_length', array(':value', 3)),
array('max_length', array(':value', 6)),
)
);
);
}
这就是我管理编辑操作的方式:
public function action_edit()
{
$brand = ORM::factory('brand', $this->request->param('id'));
if (!$brand->loaded())
{
throw new Kohana_Exception('Brand not found.');
}
$this->template->title = __('Edit Brand');
$this->template->content = View::factory('brands/edit')
->set('brand', $brand)
->bind('errors', $errors);
if ($this->request->method() === Request::POST)
{
try
{
$brand->values($this->request->post());
$brand->save();
// Success! You probably want to set a session message here.
$this->request->redirect($this->request->uri());
}
catch(ORM_Validation_Exception $e)
{
// Fail!
$errors = $e->errors('brand');
}
}
}
在我看来:
<?php if ($errors) {?>
<!-- display errors here -->
<?php } ?>
<?php echo Form::open()?>
<fieldset>
<div class="field">
<?php echo
Form::label('name', __('Name')),
Form::input('name', $brand->name)
?>
</div>
<?php echo Form::submit('save', 'Save')); ?>
</fieldset>
<?php echo Form::close()?>
如您在 View 中所见,我没有进行任何条件检查以查看在表单字段中显示的内容,因为它由模型中的数据管理,而模型中的数据由 Controller 管理。
希望这对您有所帮助,如果您需要进一步说明,请提出。
关于php - Kohana ORM 和验证,有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9123684/
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..
我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po
尝试通过RVM将RubyGems升级到版本1.8.10并出现此错误:$rvmrubygemslatestRemovingoldRubygemsfiles...Installingrubygems-1.8.10forruby-1.9.2-p180...ERROR:Errorrunning'GEM_PATH="/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/ruby-1.9.2-p180@global:/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/rub
我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
我的最终目标是安装当前版本的RubyonRails。我在OSXMountainLion上运行。到目前为止,这是我的过程:已安装的RVM$\curl-Lhttps://get.rvm.io|bash-sstable检查已知(我假设已批准)安装$rvmlistknown我看到当前的稳定版本可用[ruby-]2.0.0[-p247]输入命令安装$rvminstall2.0.0-p247注意:我也试过这些安装命令$rvminstallruby-2.0.0-p247$rvminstallruby=2.0.0-p247我很快就无处可去了。结果:$rvminstall2.0.0-p247Search
由于fast-stemmer的问题,我很难安装我想要的任何rubygem。我把我得到的错误放在下面。Buildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingfast-stemmer:ERROR:Failedtobuildgemnativeextension./System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/rubyextconf.rbcreatingMakefilemake"DESTDIR="cleanmake"DESTDIR=
我有一些非常大的模型,我必须将它们迁移到最新版本的Rails。这些模型有相当多的验证(User有大约50个验证)。是否可以将所有这些验证移动到另一个文件中?说app/models/validations/user_validations.rb。如果可以,有人可以提供示例吗? 最佳答案 您可以为此使用关注点:#app/models/validations/user_validations.rbrequire'active_support/concern'moduleUserValidationsextendActiveSupport:
当我的预订模型通过rake任务在状态机上转换时,我试图找出如何跳过对ActiveRecord对象的特定实例的验证。我想在reservation.close时跳过所有验证!叫做。希望调用reservation.close!(:validate=>false)之类的东西。仅供引用,我们正在使用https://github.com/pluginaweek/state_machine用于状态机。这是我的预订模型的示例。classReservation["requested","negotiating","approved"])}state_machine:initial=>'requested