2011-12-28 2 views
2

rails-cast #237에 따르면 동적 특성을 쉽게 구현해야했습니다. 레일즈 콘솔에 객체를 만들려고 할 때 몇 가지 오류가 발생했지만. 제발 조언.레일에서의 동적 접근 가능

다음과 같이 내가 점점 오전 오류 :

ruby-1.9.3-p0 :005 > User.new :username => "johnsmith", :email => "[email protected]", :password => "changethis" 
ArgumentError: wrong number of arguments (1 for 0) 
    from /Volumes/Terra-Nova/jwaldrip/Sites/theirksome/config/initializers/accessible_attributes.rb:6:in `mass_assignment_authorizer' 
    from /Volumes/Terra-Nova/jwaldrip/.rvm/gems/ruby-1.9.3-p0/gems/activemodel-3.1.3/lib/active_model/mass_assignment_security.rb:209:in `sanitize_for_mass_assignment' 
    from /Volumes/Terra-Nova/jwaldrip/.rvm/gems/ruby-1.9.3-p0/gems/activerecord-3.1.3/lib/active_record/base.rb:1744:in `assign_attributes' 
    from /Volumes/Terra-Nova/jwaldrip/.rvm/gems/ruby-1.9.3-p0/gems/activerecord-3.1.3/lib/active_record/base.rb:1567:in `initialize' 
    from (irb):5:in `new' 
    from (irb):5 
    from /Volumes/Terra-Nova/jwaldrip/.rvm/gems/ruby-1.9.3-p0/gems/railties-3.1.3/lib/rails/commands/console.rb:45:in `start' 
    from /Volumes/Terra-Nova/jwaldrip/.rvm/gems/ruby-1.9.3-p0/gems/railties-3.1.3/lib/rails/commands/console.rb:8:in `start' 
    from /Volumes/Terra-Nova/jwaldrip/.rvm/gems/ruby-1.9.3-p0/gems/railties-3.1.3/lib/rails/commands.rb:40:in `<top (required)>' 
    from script/rails:6:in `require' 
    from script/rails:6:in `<main>' 

/models/user.rb :

class User < ActiveRecord::Base 

    # Attributes 
    attr_accessible :username, :email, :password, :password_confirmation, :is_admin 
    attr_accessor :password 

    # Callbacks 
    before_save :encrypt_password 

    # Relationships 
    has_many :irks 

    # Validation 
    validates_confirmation_of :password 
    validates_presence_of :password, on: :create 
    validates :password, presence: true, length: { in: 3..20 } 

    validates :username, presence: true, uniqueness: true, length: { in: 3..20 } 
    validates :email, presence: true, email: true, uniqueness: true 

    # User Authentication 
    def self.authenticate(email, password) 
     user = find_by_email(email) 
     if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt) 
      user 
     else 
      nil 
     end 
    end 

    # Password Encryption 
    def encrypt_password 
     if password.present? 
      self.password_salt = BCrypt::Engine.generate_salt 
      self.password_hash = BCrypt::Engine.hash_secret(password, password_salt) 
     end 
    end 
end 

/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 

답변

1

정확히 무엇을 하려는지 또는이 mass_assignment_authorizer의 목적이 무엇인지 확실하지 않습니다. 질량 할당을 막는 더 쉬운 방법이있는 것처럼 보입니다. 즉, 나는 마지막으로 couple paragraphs of the railscast을 읽었으며, 일단이 이니셜 라이저가 생기면 객체를 만들 때 이니셜 라이저에 인수를 전달할 수없는 것처럼 보입니다. 가능한 경우에도 속성을 설정하지 않습니다 ...

컨트롤러에서 액세스 할 수있는 옵션을 만들기 작업에도 적용해야합니다. 우리가 이것을 단지 적용한다면 그것은 작동하지 않을 것입니다.

@article = Article.new(params[:article]) 
@article.accessible = :all if admin? 

이 작동하지 않는 이유는 시간에 우리는 너무 늦기 접근 설정 한 있도록 질량 할당이 새 통화에서 일어나는 것입니다. 우리는 속성을 할당하는 것으로부터 새로운 Article을 생성하는 것을 분리해야하고, 두 속성 사이에 접근 할 수 있도록 호출을 전달해야합니다.

그래서 지금 당신이 수동처럼, 당신이 원하는 속성을 할당 먼저, 그것을 만들 클래스에 :all로 접근 설정해야합니다 귀하의 모델 중 하나의 속성을 설정하기 위해 같은 날에 보이는 같은 : 그것은 여분 약간의 작업을 구현하기 때문에

u = User.create 
u.accessible = :all if current_user.is_admin? # or whatever the conditional is for the admin user 
u.update_attributes(:username => "johnsmith", :email => "[email protected]", :password => "changethis") 

사용 권한에 따라 접근이 필요합니다 얼마나 많은 속성에 따라,이 모듈을 건너 뛰는 더 나을 수 있습니다. 하나 또는 두 개의 모델에 대한 속성이 몇 개인 경우 자체 메소드 및 attr_accessible을 사용하여 수동으로이 기능을 구현하는 것이 나을 수 있습니다. this article about ruby accessors을 읽어보고이 플러그인을 사용하지 않고 원하는 결과를 얻을 수 있는지 확인하십시오.

+0

내가 수행하려고하는 유일한 작업은 사용 권한에 따라 특정 특성을 액세스 가능하게 만드는 것입니다. A.k.a. 개체를 소유하거나 관리자입니다. –

+0

railscast를보고 다시 설명을 읽은 후 그것에 대한 의견을 변경했습니다. 나는 똑똑한 해결책이라고 생각한다. 즉, 레일 스 캐스트가 구식이 아니며 '레일 3.1'과 호환되지 않는 것처럼 보입니다. [내가 사용하는 레일 버전의 ActiveRecord에 대한 문서는 attr_accessible에서 읽었을 것입니다.] (http://api.rubyonrails.org/classes/ActiveModel/MassAssignmentSecurity/ClassMethods.html#method-i-attr_accessible). 이제는 역할 단위로 액세스 할 수있는 특성을 정의 할 수 있으므로 사용하기 쉽고 사용중인 모듈이 불필요한 것처럼 보입니다. – Batkins