· 1 min read
Screencast: attr_accessible dynamisch setzen
Download:
Download(16 MB, 9:12) Alternativer Download für iPod & Apple TV(15 MB, 9:12)
Resourcen:
- Episode 26: Hackers Love Mass Assignment
- Episode 158: Factores not Fixtures
- RDocs for attr_accessible
- Full episode source code
Quellcode:
[ruby] # config/initializers/accessible_attributes.rb class ActiveRecord::Base attr_accessible attr_accessor :accessible private def mass_assignment_authorizer if accessible == :all self.class.protected_attributes else super + (accessible || []) end end end
# models/article.rb class Article < ActiveRecord::Base attr_accessible :name, :content end
# articles_controller.rb def create @article = Article.new @article.accessible = :all if admin? @article.attributes = params[:article] if @article.save flash[:notice] = “Successfully created article.” redirect_to @article else render :action => ‘new’ end end
def update @article = Article.find(params[:id]) @article.accessible = :all if admin? if @article.update_attributes(params[:article]) flash[:notice] = “Successfully updated article.” redirect_to @article else render :action => ‘edit’ end end [/ruby]