如何使用 Ruby on Rails 关联两个字段?
刚刚开始使用 Ruby on Rails,看看它是什么样的。
我有一个带有 id 的用户模型和一个带有 adderId 的帖子模型。 post模型的adderId应该是创建它的用户的用户id。
我如何将这些与 Ruby on Rails 联系起来?
Just starting to use Ruby on Rails to see what its like.
I have a user model with an id and a post model with an adderId. The adderId of the post model should be the user id of the user that created it.
How can I relate these with Ruby on Rails?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Rails 的外键约定将为您的 Post 模型提供 user_id 列,而不是 adderId。您可以打破约定,但这需要稍微更多的配置,如下所示:
如果您给 Post 提供了 user_id,则可以这样做:
我建议您查看 Rails Guide for Active Record Associations,其中涵盖了上述所有内容以及更多内容。
The Rails convention for foreign keys would give your Post model a user_id column rather than adderId. You can break the convention, but that requires slightly more configuration, as below:
If you gave Post a user_id instead, you could do this:
I'd recommend taking a look at the Rails Guide for Active Record Associations, which covers all of the above and plenty more.
看起来这个问题似乎正在做你想做的事情。
抱歉,如果我误解了你的问题,我也是 Ruby on Rails 的新手。
It looks like this question seems to be doing what you're trying to do.
Sorry if I misunderstood your question, I too am new to Ruby on Rails.