因此,我在一些关于“使用模型关联”的书中读到了一些技巧,它鼓励开发人员使用构建方法,而不是通过setter放置I。
假设您的模型中有多个has_many关系。那么,创建模型的最佳实践是什么呢?
例如,假设您有models文章、用户和组。
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有没有更干净的方法?
谢谢!
发布于 2011-02-27 00:59:31
这应该更干净一点。
@article.subdomain = current_subdomain发布于 2011-02-27 01:32:22
我唯一能想到的就是合并带有params的子域:
@article = current_user.articles.build(params[:article].merge(:subdomain => current_subdomain))https://stackoverflow.com/questions/5128336
复制相似问题