Rails 提示 - “使用模型关联”
因此,我在一些书中读到了有关“使用模型关联”的技巧,该技巧鼓励开发人员使用构建方法而不是通过设置器放置 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这应该更干净一点。
This should be a little cleaner.
我唯一能想到的是将子域与参数合并:
The only thing I can think of is merging the subdomain with params: