如何使用 Ruby on Rails 关联两个字段?

发布于 2024-08-05 13:08:19 字数 147 浏览 3 评论 0原文

刚刚开始使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

柒夜笙歌凉 2024-08-12 13:08:19

Rails 的外键约定将为您的 Post 模型提供 user_id 列,而不是 adderId。您可以打破约定,但这需要稍微更多的配置,如下所示:

class User < ActiveRecord::Base
  has_many :posts, :foreign_key => :adderId
end

class Post < ActiveRecord::Base
  belongs_to :adder, :class_name => "User", :foreign_key => :adderId
end

如果您给 Post 提供了 user_id,则可以这样做:

class User < ActiveRecord::Base
  has_many :posts
end

class Post < ActiveRecord::Base
  belongs_to :user
end

我建议您查看 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:

class User < ActiveRecord::Base
  has_many :posts, :foreign_key => :adderId
end

class Post < ActiveRecord::Base
  belongs_to :adder, :class_name => "User", :foreign_key => :adderId
end

If you gave Post a user_id instead, you could do this:

class User < ActiveRecord::Base
  has_many :posts
end

class Post < ActiveRecord::Base
  belongs_to :user
end

I'd recommend taking a look at the Rails Guide for Active Record Associations, which covers all of the above and plenty more.

墨落画卷 2024-08-12 13:08:19

看起来这个问题似乎正在做你想做的事情。

抱歉,如果我误解了你的问题,我也是 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文