我可以更改 Rails 中新模型实例的分配顺序吗
我有两个属性,“a_value”和“b_id”。 (不是他们的真实姓名。)“a_value”存储在文件系统上,使用模型“B”中的一些信息,由“b_id”引用。
所以,我的 params 对象看起来像:
params[:foo] = {"a_value"=>"nifty value","b_id"=>"38"}
例如。
现在,在 foo_controller.rb 中:
foo = Foo.new(params[:foo])
但这失败了。
ActiveRecord::RecordNotFound: Couldn't find Foo without an ID
在 Foo.a_value=(value) 中,我看起来
...
self.my_path = self.b_id.the_path
...
Rails 正在按字母顺序进行分配,并且当 b_id 不存在时会出现恐慌,即使它存在于 params 哈希中并通过验证。
我可以强制执行此作业的顺序吗?或者我可以创建一个 before_filter 来在剩余的批量分配发生之前执行 b_id 分配吗?
I have two attributes, 'a_value' and 'b_id'. (Not their real names.) 'a_value' is stored on the file system, using some information from model 'B', referenced by 'b_id'.
So, my params object looks like:
params[:foo] = {"a_value"=>"nifty value","b_id"=>"38"}
for example.
Now, in foo_controller.rb:
foo = Foo.new(params[:foo])
But this fails with.
ActiveRecord::RecordNotFound: Couldn't find Foo without an ID
In Foo.a_value=(value) I have
...
self.my_path = self.b_id.the_path
...
It looks like Rails is doing the assignments in alphabetical order and panicking when b_id isn't there, even though it's present in the params hash and passes validation.
Can I force the order in which this assignment is done? Or can I create a before_filter that will do the b_id assignment before the remainder of the mass assignment happens?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想通了!
执行此操作的方法如下:
您必须确保验证按顺序进行,但它有效。
如果您可以为属性指定部分排序而不必重命名它们,那就更好了。
I figured it out!
The way to do this is as follows:
You have to make sure your validations are in order, but it works.
It would be nicer if you could specify a partial ordering for your attributes without having to rename them.