2017-02-15 60 views
0

enter image description here重構記錄檢索

我上面的代碼和下面的路線的resources

resources :products, only:[:index] do 
    resources :orders, :path => 'order', only:[:new, :create], 
    path_names: {new: ""} 
end 

我想知道,如果在#4和#代碼,因爲他們」 9可重構重做同樣的事情,我讀過Ruby中的編程總是鼓勵DRY代碼。學習在這裏成爲一個更好的程序員。感謝您的提示和建議。

+0

請添加代碼片段而不是圖片 –

回答

0

是的,你可以把它添加到before_actionnewcreate行動

現在@product刪除之前newcreate行動

before_action :find_product, only: [:new, :create] 

private 

def find_product 
    @product = Product.find(params[:product_id]) 
end 
1

如迪帕克提到的將被分配,before_action是一個想法。就個人而言,我更喜歡懶惰的訪問者。它的優點是:

  • 這些模型是直接在動作中引用的,而不是文件中的其他地方。很容易看出某個動作使用了哪些模型。
  • 依賴關係自動計算出來。如果使用order,則自動加載product,無需手動加載。

代碼應該是這樣的:

def new 
    product 
end 

def create 
    if order.save 
    redirect_to(products_path) 
    else 
    render(:new) 
    end 
end 

private 

def product 
    @product ||= Product.find(params[:product_id]) 
end 

def order 
    @order ||= product.orders.build(order_params) 
end 

請注意,我做了兩個小的變化(你可以擺脫):

  1. 我建(而不是創建它的訂單)並測試order.save是否返回真值。
  2. 我不會在閃存中傳遞錯誤。我假設他們的渲染格式爲new.html.erb

如果它們不適合您的應用程序,請隨時放棄這些更改。

+1

好方法,儘管在'new'中調用'product'不是很具描述性。我會考慮在product的定義下面添加'alias:set_product:product' – fylooi