[英]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_id
將topic_id
的user_id
或topic_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.