Rails 控制器何时没有 ActiveRecord 模型?
我正在尝试创建一个不使用 ActiveRecord 框架的 Rails Web 应用程序,因为我没有关系数据库后端。
到目前为止,我成功创建了一个简单的示例应用程序,它非常适合列出、显示和编辑我的记录。
然而,我在记录创建方面遇到了一些问题。
问题是,如果模型类不继承自 ActiveRecord::Base,控制器类的行为方式将不同。
从控制器的角度来看,在模型继承自 ActiveRecord::Base 的经典活动记录模型架构中,记录的创建似乎遵循以下顺序:
- controller.new:创建非持久记录,呈现输入表单
- controller.create:设置用户输入记录、持久存储……。
然而,在模型不是 ActiveRecord 的情况下,我们得到以下序列:
- controller.new
- controller.update
现在当然这有点奇怪,因为我们跳过了创建方法,所以它会导致零实例错误!
我非常确定这种行为是由模型中应该实现的东西决定的,但是我无法找到什么(可能是因为我是 Rails 的绝对初学者)
所以如果这里有人对我应该做什么有一些指示正在寻找/实施以解决这种情况并在两种情况下具有相同的行为,我将非常感激。
谢谢,
I'm trying to create a rails web app that does not use ActiveRecord framework as I have no relational database back end.
So far I managed to create a simple example application that works perfectly for listing, showing and editing my records.
However I'm facing some problems when it comes to the record creation.
The issue is that the controller class does not behave in the same manner if the model class does not inherit from ActiveRecord::Base.
From the controller's point of view, in a classic active record model schema where the model inherits from ActiveRecord::Base, the creation of a record seems to follow this sequence :
- controller.new : creation of a non persistent record, rendering the input form
- controller.create : set up the record with user input, persistant storage , ….
However in the case where the model is not a ActiveRecord we get the following sequence :
- controller.new
- controller.update
Now of course this is a little bit strange because we're skipping the creation method so it will lead to a nil instance error !
I'm pretty certain that this behavior is dictated by something that should be implemented in the model, however I was unable to find what (probably because I'm an absolute beginner with rails )
So if anyone here has some pointers on what I should be looking/implementing in order to solve this situation and have the same behaviour in both cases, I'd be realy grateful.
Thanks,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
让您的自定义模型实现
MyModel#new_record?
方法(实例方法),您将获得所需的行为。当
new_record?
返回true时,会去create,当返回false时,会去update。Have your custom model implement the
MyModel#new_record?
method (instance method) and you will have the desired behavior.When
new_record?
returns true, it will go to create, and when it returns false it will go to update.