そのため、「モデルの関連付けを使用する」というヒントに関する本を読んだことがあります。これは、開発者がセッターを介してIDを配置する代わりにビルドメソッドを使用することを奨励しています。
モデルに複数の has_many 関係があるとします。モデルを作成するためのベストプラクティスは何ですか?
たとえば、Article、User、および 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
および 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
よりクリーンな方法はありますか?
ありがとう!