SkRoR
SkRoR

Reputation: 1199

How to solve undefined local variable or method error

I have three tables: RM, GenericUser, Properties.

RM fields: id, name

GenericUser fields: id, mobile, rm_id, name.

Properties fields id, image, rm_id, generic_user_id, property_name.

RM is creating GenericUser, so that rm_id is automatically entered in GenericUser table.

After that generic user logs in and creates property, so when generic user creates property, rm_id should fetch from generic user table and should enter in property table field where rm_id is.

I have model relation like this.

class Rm < ActiveRecord::Base
    acts_as :user
    has_many :generic_users
end

class Property < ActiveRecord::Base
    belongs_to :generic_user
end

class GenericUser < ActiveRecord::Base
    belongs_to :rm
    has_many :properties
end

My generic_users propertiescontroller:

def create
    @property = Property.new(property_params)
    @gu=GenericUser.select(:rm_id).where(:id=>current_user.specific.id)
    @[email protected]_id
   logger.info @gu.inspect
    logger.info @property.rm_id.inspect
    if @property.save
        redirect_to  :back, notice: 'Property was successfully created.' 
    else
        render :new
    end
end

I am getting this error:

enter image description here

when i inspect @gu iam getting this

#<ActiveRecord::Relation [#<GenericUser id: 1, mobile: "8776766777", address: "reewtrwt", created_at: "2016-02-18 07:41:06", updated_at: "2016-02-19 08:59:13", dob: "", rm_id: "4", category_id: "1",>]> Completed 500 Internal Server Error in 73ms (ActiveRecord: 1.9ms)

how i will save this GenericUser rm_id(ie; rm_id :4) to properties table field rm_id?

Upvotes: 0

Views: 1623

Answers (2)

Hieu Pham
Hieu Pham

Reputation: 6707

Your error is in these lines:

@gu = GenericUser.select(:rm_id).where(:id=>current_user.specific.id)
@property.rm_id = @gu.rm_id

Explanation:

@gu was returned as Active Record Relations, so you couldn't call @gu.rm_id

Solution - Try something like this:

@gu = GenericUser.find(current_user.specific.id)
@property.rm_id = @gu.rm_id

@gu is now a GenericUser, so you can call rm_id on it

Upvotes: 1

Albert Paul
Albert Paul

Reputation: 1208

You've already selected rm_id in @gu. You don't need to call it again.

Change this,

@[email protected]_id

To this,

 @property.rm_id = @gu

Upvotes: 0

Related Questions