Rubytastic
Rubytastic

Reputation: 15491

rails pass variable to model from controller not working

Im trying to pass a variable from controller to my form to no avail.

Its working in another controller but cannot make it work for new user registrations.

  def update
    @profile = Profile.find(params[:id])
    @profile.form = "signup"
    ...
  end

Inside model I can do @profile.form to get the value

This does not work for new user registrations: inside create action:

 undefined method `form=' for nil:NilClass

how to pass a variable to my model upon new user registration? User = User.new then @user.form == "signup" does not work either, i have :form in my attributes accessible list

Part of model:

  attr_accessible form
  ...
  validates :city_id, :presence => true, :if => :signup?


  def signup?
    #@profile.form == "signup"
    #@user.form == "signup"
    if self.form == "signup"
      return true
    else
      return false
    end
  end

EDIT 1: Still unable to pass a param to the model :S:S:S tried every possible way and google found solution.

The create method for my registrations#create =

  def create
    profile = Profile.new
    profile.form = "signup"

    super
  end

Upvotes: 0

Views: 2090

Answers (2)

code4j
code4j

Reputation: 4636

I am not sure what exactly your problem is . What I understand after I read your problem statement twice is that you tried to "new" a instance of Profile, assign its form attribute. And use its instance method signup? to do validation. But you get an error after on self.form because self reference to the nil Class

I think you should change profile to @profile inside the create method. Just by guess after reading ruby guide about instance variable, My thought is that declaring the instance variable that will be added dynamically inside the controller structure and later they are passed to the model. And it is always @... inside controller generated by rails g scaffold.

Just give it a try :)

Upvotes: 1

sohaibbbhatti
sohaibbbhatti

Reputation: 2682

Interesting. I believe what you want to do is have a virtual attribute 'form' of an object a certain value. I.e. does form exist in the database as well. If it doesn't you should be using attr_accessor :form Documentation

This defines the getter and setter method for form in the class where it is being invoked.

However, the error you stated is something radically different.

undefined method `form=' for nil:NilClass

This merely means a profile with the id being passed in the params does not exist. i.e. if we are updating params id = 222, a database record with id 222 does not exist for Profile.

Upvotes: 1

Related Questions