0

そのため、「モデルの関連付けを使用する」というヒントに関する本を読んだことがあります。これは、開発者がセッターを介して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

よりクリーンな方法はありますか?

ありがとう!

4

2 に答える 2

1

これは少しきれいになるはずです。

@article.subdomain = current_subdomain
于 2011-02-26T16:59:31.323 に答える
1

私が考えることができる唯一のことは、サブドメインをparamsとマージすることです:

@article = current_user.articles.build(params[:article].merge(:subdomain => current_subdomain))
于 2011-02-26T17:32:21.923 に答える