1

ActiveModel でいくつかの機能を使用しようとしていますが、すべてを機能させるのに問題があります。クラスファイルと実行中のテストを含めました。

テストは次のエラーで失敗します: ': undefined method `attr_accessible

MassAssignmentSecurity がそれを取り込み、実際に実行されているため、その理由は本当にわかりません。また、すべての ActiveModel も含めようとしましたが、それも機能しません。MassAssignmentSecurity を取り込むために include を使用するか、extend を使用するかは問題ではないようです。

初期化で「assign_attributes」を実行するためにテストでいくつかの属性を渡すと、それも失敗します。私はレールにかなり慣れていないので、本当に単純なものが欠けているだけだと思っています。

ティア。

レールの使用 3.2.12


my_class.rb

class MyClass
  include ActiveModel::MassAssignmentSecurity
  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming
  extend ActiveSupport::Callbacks

  attr_accessible :persisted, :creds

  def initialize(attributes = nil, options = {})
    @persisted = false

    assign_attributes(attributes, options) if attributes

   yield self if block_given?
  end
end

my_class_spec.rb

require 'spec_helper'

describe MyClass do
  before do
    @testcase = MyClass.new
  end
  subject { @testcase }

  it_should_behave_like "ActiveModel"

  it { MyClass.should include(ActiveModel::MassAssignmentSecurity) }

  it { should respond_to(:persisted) }
end

サポート/active_model.rb

shared_examples_for "ActiveModel" do
  include ActiveModel::Lint::Tests

  # to_s is to support ruby-1.9
  ActiveModel::Lint::Tests.public_instance_methods.map{|m| m.to_s}.grep(/^test/).each do |m|
    example m.gsub('_',' ') do
      send m
    end
   end

  def model
    subject
  end
 end
4

1 に答える 1

2

うわぁ!昨日はめちゃくちゃでした。私は自分の問題を理解したので、自分の質問に答えるかもしれません。

  1. MassAssignmentSecurity の attr_accessible は、ActiveRecord のようには機能しません。ゲッターとセッターは作成しません。作成した場合は、引き続き attr_accessor を使用する必要があります。

  2. assign_attributes は、mass_assignment_sanitizer をラップするために誰かが書いた便利な関数であり、MassAssignment Security に組み込まれたものではありません。実装例は次のとおりです。



def assign_attributes(values, options = {})
  sanitize_for_mass_assignment(values, options[:as]).each do |k, v|
    send("#{k}=", v)
  end
end
于 2013-03-14T14:14:28.443 に答える