【问题标题】:Rails tip - "Use model association"Rails 提示 - “使用模型关联”
【发布时间】:2011-02-26 16:56:55
【问题描述】:

所以,我读过一些关于提示“使用模型关联”的书,它鼓励开发人员使用构建方法而不是通过设置器放置 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

有没有更清洁的方法?

谢谢!

【问题讨论】:

  • 第一行不应该是@article = current_user.articles.build(params[:article])
  • @Dogbert:是的,错字。 tnx 用于注意,现已修复。

标签: ruby-on-rails activerecord associations controllers


【解决方案1】:

这应该更干净一些。

@article.subdomain = current_subdomain

【讨论】:

  • 是的,但我想以某种方式避免整行。但是,tnx。
【解决方案2】:

我唯一能想到的就是将子域与参数合并:

@article = current_user.articles.build(params[:article].merge(:subdomain => current_subdomain))

【讨论】:

  • 老实说,我试过了,但出于某种奇怪的原因,它没有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-05
  • 1970-01-01
相关资源
最近更新 更多