在我的Rails應用程序中,people
可以有很多projects
,反之亦然。如何在Rails has_and_belongs_to_many模型中驗證提交的ID?
class Person < ActiveRecord::Base
has_and_belongs_to_many :projects
attr_accessible :name, :person_ids
end
class Project < ActiveRecord::Base
has_and_belongs_to_many :people
attr_accessible :name, :person_ids
end
在我ProjectsController
我需要一種方法來確保沒有用戶都不能創建一個project
屬於另一個用戶的people
。現在,我的選擇框很容易被黑客攻擊,例如通過瀏覽器控制檯。
在我眼中,處理這個問題的最好方法是before_filter
。這是我想出了一個:
class ProjectsController < ApplicationController
before_filter :valid_people, :only => [ :create, :update ]
def create
@project = current_user.projects.build(params[:project])
if @project.save
flash[:success] = "Project created."
redirect_to edit_project_path(@project)
else
render :new
end
end
private
def valid_people # not working yet
if params[:project][:person_ids].present?
person = current_user.people.where(:id => params[:project][:person_ids]).first
redirect_to(root_path) unless person
end
end
end
然而,因爲我還是新到Rails我用valid_people
方法的語法掙扎。我如何檢查person_ids
是否屬於用戶?
感謝您的任何幫助。
'User'與'Person'相同嗎? – jcm
不可以。「用戶」可以有許多「人員」和「項目」。 – Tintin81
啊。你應該發佈'User'類。您的應用程序的業務規則並不總是對其他人顯而易見。 – jcm