2016-05-06 83 views
0

我想從我的控制器中分離出一些邏輯,但無法按照我想要的方式工作。我有我的一個功能,需要一個CSV文件,並進入各行到我WeighIns表:Rails 4:單獨的模型和控制器功能與驗證

# Controller (WeighIn belongs_to User) 

def bulk_upload_weigh_ins 
    import = WeighIn.import(params[:file]) 
    redirect_to import_weigh_ins_path, notice: "Weigh Ins Imported Successfully!" 
end 

然後我有CSV解析函數在我的模型

# WeighIn model  

def self.import(file) 
    CSV.foreach(file.path, headers: true) do |row| 
     hashed_row = row.to_hash 
     # VALIDATE HERE 
     WeighIn.create hashed_row 
    end 
end 

,但在創建條目之前在WeighIns表中,我希望確保散列中有屬性的相應用戶,即User.find_by(scale_id: hashed_row["scale_id"]) != nil,其中scale_id是行的一部分,而我的User表中的列也是這樣。

如何可以驗證這一點,並返回,告訴我有「不爲用戶scale_id:富」一個有用的錯誤

回答

1

您可以在任何模型或控制器做。這是大多數開發人員對可重用性的看法的設計決策:用戶授權是您模型的一般用途嗎?如果你想重新使用你的模型,你想要相同的授權方案嗎?

如果將它放入模型中,WeighIn模型應該可以訪問用戶模型或授權模型。導入函數然後可以返回true來成功。

在控制器,你可以通過使用你已經指出自己,或者更一般的條件下,用「before_action」回調,可以檢查授權稱爲實際功能之前實現授權,像

before_action :check_authorization, only: [:bulk_upload_weigh_ins] 

private 
    def check_autorization 
    render nothing:true, status: :forbidden unless (autorized_condition) 
    end 

在這兩種情況下,您都可能希望通過使用「render nothing:true,status::forbidden」或更復雜的html響應,通過渲染布局並顯示錯誤消息來返回http禁止響應(403)。在這裏,「閃光燈」通常是在,你可以在你的「重量機械/ bulk_upload_weigh_ins.html.erb」(或HAML)模板(見The Flash)使用。

flash[:alert] = "You are wrong!" 

現在,在你的行動要麼什麼都不做(呈現爲操作的默認模板),呈現一個特殊的模板或重定向用戶(其中​​一個必須做的,如果你使用before_action停止處理)。

render 'an_error_template' # in views/controller/an_error_template.html.erb or haml 

redirect_to :other_action # sends the browser to another action, flash[:alert] is still accessible there 

記住查詢閃在你的佈局或動作模板來顯示消息,如

<% flash.each do |message_type, message| %> 
    <%= content_tag(:div, message, class: "alert alert-#{message_type}") %> 
<% end %> 
+0

感謝您的詳細回覆,我肯定會採取這些措施。 –