所以,我读过一些关于技巧“使用模型关联”的书,它鼓励开发人员使用构建方法而不是通过设置器放置 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
有没有更清洁的方法?
谢谢!