mridula
mridula

Reputation: 3281

Attribute value nil

Can someone tell me why is this happening?

I have created a social networking website using Ruby on Rails. This is my first time programming with RoR.

I have a model named "Friendship" which contains an attribute "blocked" to indicate whether the user has blocked another user.

When I run the following in IRB -

friendship = u.friendships.where(:friend_id => 22).first

IRB gives me -

  Friendship Load (0.6ms)  SELECT `friendships`.* FROM `friendships` WHERE `friendships`.`user_id` = 17 AND `friendships`.`friend_id` = 22 LIMIT 1
=> #<Friendship id: 33, user_id: 17, friend_id: 22, created_at: "2012-04-07 10:29:49", updated_at: "2012-04-07 10:29:49", blocked: 1> 

As u can see, the "blocked" attribute has value '1'.

But when I run the following

1.9.2-p290 :030 > friendship.blocked    
=> nil 

- it says, the value of blocked is 'nil' and not '1'. Why is this happening? This could be a very silly mistake but I am new to RoR, so kindly help me!

I initially didn't include the accessor method for 'blocked'.. I tried that, and still its giving the same result.. Following is the Friendship model..

class Friendship < ActiveRecord::Base
    belongs_to :friend, :class_name => "User"
    validates_uniqueness_of :friend_id , :scope => :user_id

    attr_accessor :blocked
    attr_accessible :blocked
end

Here is the schema of the table:

1.9.2-p290 :009 > friendship.class
=> Friendship(id: integer, user_id: integer, friend_id: integer, created_at: datetime, updated_at: datetime, blocked: integer) 

Upvotes: 1

Views: 897

Answers (1)

fl00r
fl00r

Reputation: 83680

attr_accessor :blocked creates two methods:

def blocked
  @blocked
end

def blocked=val
  @blocked = val
end

And this rewrites AR blocked method, which should return attribute value

So you should remove this line from your code.

Upvotes: 5

Related Questions