1

I am having an active-record model Import

class Import < ActiveRecord::Base
  before_create :check_it
  def check_it
    ...
  end
end

I am having two controllers User and Question

class QuestionsController < ApplicationController
  def import_question
    @import_item = Import.new
    ...
  end
end

class UsersController < ApplicationController
  def import_user
    @import_item = Import.new
    ...
  end
end

I want to skip the check_it method in the Import model for UsersController.

Please help..

Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
webster
  • 3,902
  • 6
  • 37
  • 59

1 Answers1

1

The question is, do you really want to do this?

I don't know that the check_it method does, but I think a better way would be to simple call check_it if you need it, for example:

 @import_item = Import.new
 @import_item.check_it

This makes your code more explicit, and less "magical".

If you really do want to do this, you could do this in your model:

attr_accessor :skip_check_it
before_create :check_it, unless: -> { @skip_check_it }

And then create it like so:

@import_item = Import.new
@import_item.skip_check_it = true
Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
  • I am getting the following error: ActiveModel::MassAssignmentSecurity::Error at /questions/import Can't mass-assign protected attributes: skip_check_it. Thanks @Carpetsmoker – webster Dec 12 '14 at 06:44
  • 1
    @RahulV I didn't test it with Rails 3, but this works with Rails 4. According to [this page](http://stackoverflow.com/questions/10574957/activemodelmassassignmentsecurityerror-cant-mass-assign-protected-attribut), using `@import_item.skip_check_it = true` should work in any case. – Martin Tournoij Dec 12 '14 at 06:47