在我的 Rails 应用程序中,我invoices
有很多projects
.
模型:
class Invoice < ActiveRecord::Base
attr_accessible :project_id
end
控制器:
class InvoicesController < ApplicationController
before_filter :authorized_user, :only => [ :show, :edit, :destroy ]
before_filter :authorized_project, :only => [ :create, :update ]
def create # safe
@invoice = @project.invoices.build(params[:invoice])
if @invoice.save
flash[:success] = "Invoice saved."
redirect_to edit_invoice_path(@invoice)
else
render :new
end
end
def update # not safe yet
if @invoice.update_attributes(params[:invoice])
flash[:success] = "Invoice updated."
redirect_to edit_invoice_path(@invoice)
else
render :edit
end
end
private
def authorized_user
@invoice = Invoice.find(params[:id])
redirect_to root_path unless current_user?(@invoice.user)
end
def authorized_project
@project = Project.find(params[:invoice][:project_id])
redirect_to root_path unless current_user?(@project.user)
end
end
我最大的担忧是,有朝一日,恶意用户可能会创建一个invoice
属于project
另一个用户的。
现在感谢这个板上一些人的帮助,我设法想出了一个before_filter
确保在创建项目时不会发生这种情况的方法。
问题是我不明白如何将此过滤器也应用于update
操作。
由于更新操作没有使用 Rails 的build
功能,我根本不知道如何进入@project
那里。
有人可以帮忙吗?