首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails技巧-“使用模型关联”

Rails技巧-“使用模型关联”
EN

Stack Overflow用户
提问于 2011-02-27 00:56:56
回答 2查看 187关注 0票数 0

因此,我在一些关于“使用模型关联”的书中读到了一些技巧,它鼓励开发人员使用构建方法,而不是通过setter放置I。

假设您的模型中有多个has_many关系。那么,创建模型的最佳实践是什么呢?

例如,假设您有models文章、用户和组。

代码语言:javascript
复制
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:

代码语言:javascript
复制
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

有没有更干净的方法?

谢谢!

EN

回答 2

Stack Overflow用户

发布于 2011-02-27 00:59:31

这应该更干净一点。

代码语言:javascript
复制
@article.subdomain = current_subdomain
票数 1
EN

Stack Overflow用户

发布于 2011-02-27 01:32:22

我唯一能想到的就是合并带有params的子域:

代码语言:javascript
复制
@article = current_user.articles.build(params[:article].merge(:subdomain => current_subdomain))
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5128336

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档