【发布时间】:2013-09-27 15:28:50
【问题描述】:
在我的 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
我最担心的是,有朝一日,恶意用户可能会创建一个属于另一个用户的project 的invoice。
现在感谢这个板上的一些人的帮助,我设法提出了一个before_filter,以确保在创建项目时不会发生这种情况。
问题是我不明白如何将此过滤器也应用于update 操作。
由于更新操作没有使用 Rails 的 build 函数,我根本不知道如何在其中获取我的 @project。
有人可以帮忙吗?
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-3 activerecord associations