如何处理异或条件、rails、外键和 sqlite 数据库?
我想要的是,用 Rails 3.1 以某种方式构建它:
如果 A
已为 b_id
设置了 id,则应该无法为 c_id
设置 ID。当然反之亦然。
我希望我可以在数据库级别进行迁移(检查约束?)。这有可能吗? 或者在带有验证的模型中执行此操作是否更经济?
我的环境:
- Ruby 1.9.3
- Rails 3.1.3
- SQLite 3.7.3
What I want is, building this somehow with Rails 3.1:
If A
has set an id for b_id
, it shouldn't be possible to setting an id for c_id
. And for sure vice versa too.
I wish I could do at the database level from a migration (check constraint?). Is this somehow possible?
Or is it more affordable to do this in the model with validations?
My environment:
- Ruby 1.9.3
- Rails 3.1.3
- SQLite 3.7.3
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以通过多态关联来实现此目的,尽管模式看起来与您所拥有的不完全相同,但您可以实现相同的目标,让项目
A
属于B
> 或C
但绝不能两者兼而有之。您可以在这里阅读更多内容: http://guides.rubyonrails.org/association_basics.html#polymorphic -associations
在该链接给出的示例中,
A
是他们的Picture
,Employee
和Proudct
是您的B
和C
:(从上面链接的源代码复制):
You can accomplish this through polymorphic associations, altho the schema won't look exactly like what you have, you can accomplish the same goal, having an item
A
belong to either aB
or aC
but never to both.You can read more here: http://guides.rubyonrails.org/association_basics.html#polymorphic-associations
In the example given on that link,
A
is theirPicture
, andEmployee
andProudct
are yourB
andC
:(copied from source linked above):
我肯定会为此编写验证 - 通过验证向用户提供良好的错误消息更容易。我还想用数据库约束来备份它。看起来检查约束确实可以完成这项工作。
我发现 Rails 不支持此操作,因此您需要使用原始 sql 创建表。您还需要将模式转储器更改为
:sql
,因为 Rails 无法生成实际描述这一点的schema.rb
。我写了这个迁移
然后在rails控制台中
您可以创建一个既没有设置x_id也没有设置y_id的行。你可以通过改变约束来改变这个,
似乎对我有用
I would definitely write validations for this - it's easier to provide good error messages to a user from a validations. I'd also like to back it up with a database constraint. It looks like check constraints can indeed do the job.
Rails has no support for this that I could find so you'll need to create the table with raw sql. You'll also need to change the schema dumper to
:sql
as rails won't be able to produce aschema.rb
that describes this actually.I wrote this migration
Then in the rails console
As it is you can create a row with neither x_id nor y_id set. You could change this by changing the constraint,
seemed to work for me