Rails 提示 - “使用模型关联”

发布于 2024-10-19 06:26:44 字数 970 浏览 1 评论 0原文

因此,我在一些书中读到了有关“使用模型关联”的技巧,该技巧鼓励开发人员使用构建方法而不是通过设置器放置 id。

假设您的模型中有多个 has_many 关系。那么创建模型的最佳实践是什么?

例如,假设您有模型文章、用户和组。

class Article < ActiveRecord::Base
  belongs_to :user
  belongs_to :subdomain
end

class User < ActiveRecord::Base
  has_many :articles
end

class Subdomain < ActiveRecord::Base
  has_many :articles
end

和 ArticlesController:

class ArticlesController < ApplicationController
  def create
    # let's say we have methods current_user which returns current user and current_subdomain which gets current subdomain
    # so, what I need here is a way to set subdomain_id to current_subdomain.id and user_id to current_user.id
    @article = current_user.articles.build(params[:article])
    @article.subdomain_id = current_subdomain.id
    # or Dogbert's suggestion
    @article.subdomain = current_subdomain
    @article.save
  end
end

有没有更干净的方法?

谢谢!

So, I've read in some book about tip "Use model association", which encourages developers to use build methods instead of putting ids via setters.

Assume you have multiple has_many relationships in your model. What's best practise for creating model then ?

For example, let's say you have models Article, User and Group.

class Article < ActiveRecord::Base
  belongs_to :user
  belongs_to :subdomain
end

class User < ActiveRecord::Base
  has_many :articles
end

class Subdomain < ActiveRecord::Base
  has_many :articles
end

and ArticlesController:

class ArticlesController < ApplicationController
  def create
    # let's say we have methods current_user which returns current user and current_subdomain which gets current subdomain
    # so, what I need here is a way to set subdomain_id to current_subdomain.id and user_id to current_user.id
    @article = current_user.articles.build(params[:article])
    @article.subdomain_id = current_subdomain.id
    # or Dogbert's suggestion
    @article.subdomain = current_subdomain
    @article.save
  end
end

Is there a cleaner way ?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

青衫儰鉨ミ守葔 2024-10-26 06:26:44

这应该更干净一点。

@article.subdomain = current_subdomain

This should be a little cleaner.

@article.subdomain = current_subdomain
末蓝 2024-10-26 06:26:44

我唯一能想到的是将子域与参数合并:

@article = current_user.articles.build(params[:article].merge(:subdomain => current_subdomain))

The only thing I can think of is merging the subdomain with params:

@article = current_user.articles.build(params[:article].merge(:subdomain => current_subdomain))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文