1
假設您有一個Question
和Answer
模型,並且從questions#show
頁面(如StackoverFlow)提交了新答案。避免父控制器和子控制器的控制器動作之間耦合的模式
除非questions#show
和answers#create
行動加載相同的數據,如果有一個新的答案驗證錯誤的answers#create
將拋出一個異常(通常在零類沒有方法)。這不是一個主要問題,但是當您添加過濾器和其他類型的數據時,代碼開始聞起來,並且您在兩個操作之間緊密耦合。改變一個需要改變另一個 - 容易忘記的東西。
我想知道有什麼經驗的Rails開發人員做什麼,如果有的話,以避免這種耦合?
# Assume Discussion = Question, and Response = Answer
# Discussions#show
def show
@discussion = Discussion.find(params[:id]) # The question
@responses = @discussion.responses.includes(:author) # Existing answers
@response = @discussion.responses.build # New answer object for the form
order = 'users.role'
if params[:filter].present?
order = case params[:filter]
when 'new'
then 'responses.created_at DESC'
end
end
@responses = @responses.order(order)
end
現在讓我們來看看responses#create
行動,這已加載相同數據render
工作(如果驗證失敗):
# Responses#create
def create
# @discussion is loaded using a before filter
@response = @discussion.responses.build(params[:response])
@response.author = current_user
@responses = @discussion.responses.includes(:author)
order = 'users.role'
if params[:filter].present?
order = case params[:filter]
when 'new'
then 'responses.created_at DESC'
end
end
@responses = @responses.order(order)
respond_to do |format|
if @response.save
format.html { redirect_to @discussion }
format.js
else
format.html { render 'discussions/show' } # fails if discussions#show and responses#new do not load the same data.
end
end
end