簡體   English   中英

創建帶有兩個belongs_to關聯的模型的最佳實踐?

[英]Best practice for creating a model with two belongs_to associations?

這是我經常遇到的一致性問題。

讓我們考慮一個典型的論壇:

  • 用戶可以創建帖子
  • 帖子屬於主題
  • 帖子也屬於創建它們的用戶

在這兩個選項之間進行選擇的最佳實踐是什么:

# Initialize @post on the User
def create
  @post = current_user.posts.build(params[:post])
  @post.topic_id = @topic.id
  if @post.save
    ...
  end
end

要么

# Initialize @post on the Topic
def create
  @post = @topic.posts.build(params[:post])
  @post.user_id = current_user.id
  if @post.save
    ...
  end
end

還是有更好的方法,考慮到在以上示例中, topic_idtopic_iduser_idtopic_id添加到attr_accesssible (感覺很hacky)?

我設法找到的最干凈的方法是使用CanCan:當規則can :create, Post, :user_id => user.id並在控制器中添加load_resource時,它將設置屬性。

但這並不總是合適的。 有一些通用的解決方案可以一口氣初始化嵌套的對象。

更新。 我想出了另一個選擇:

@post = @topic.posts.where(user_id: current_user.id).build(params[:post])

一般而言,所有這些方法都違反了Demeter定律 最好將其封裝在模型的方法中,如下所示:

class Topic < ActiveRecord::Base
  def new_post(params={}, author=nil)
    posts.build(params).tap {|p| p.user = author}
  end
end

然后在控制器中:

@post = @topic.new_post(params[:post], current_user)

您永遠不需要使用ID或attr_accessible。 如果用戶has_many帖子和一個主題has_many帖子超出了您的能力范圍

# Initialize @post on the User
def create
  @post = current_user.posts.build(params[:post])
  @post.topic = @topic #assuming you've gotten the topic from somewhere
  if @post.save
    ...
  end
end 

從用戶或從主題進行構建實際上並沒有太大區別,但是從用戶看來對我來說更自然。

我更喜歡

@post = @topic.posts.build(params[:post])
@post.user = current_user

盡管我看不到其他方法有任何問題,但通過主題構建帖子對我來說更自然(因為帖子大多顯示在其主題的上下文中,而不是用戶本身)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM