如何向对象添加新属性?

时间:2021-06-14 16:44:50

I'm trying to add a new property to an object created through my User model.

我正在尝试向通过User模型创建的对象添加新属性。

a = User.find(7)

I get:

我明白了:

#<User id: 7, name: "Ewah", email: "stugnuz@yahoo.it", password_salt: "t4vPG0hgQVQMyIFeri6", persistence_token: "98f0cdfcb9462f3f74b1ae6ef48f0d72a015c6e04adda95fcd0...", login_count: 387, failed_login_count: 0, current_login_at: "2011-03-15 08:03:54", last_login_at: "2011-03-14 23:17:45", current_login_ip: "93.34.49.190", last_login_ip: "93.34.38.47", score: 2726, level: 7, created_at: "2010-10-13 22:33:21", updated_at: "2011-03-28 13:28:40", admin: true, avatar_file_name: "11.jpg", avatar_file_size: 78456, avatar_content_type: "image/jpeg", perishable_token: "PXTFtiMBxcoH3Iv7TmRh", score_this_week: 0, get_news: true, get_notices: true, bio: "Ho perso per strada Minnie anche in onore di Ken Sa...", invitation_id: nil, can_approve: false, no_score: false, facebook_uid: "1052260327", facebook_session_key: "", crypted_password: "05e5080268598607f5d1ece82db1b4d4c6ae12deeb880896ad2...", oauth2_token: "141832835841718|545eae41205d7a2ccb37d7c0-1052260327...", votes_count: 208, post_to_facebook: true, tutorial_step: 2, private: false, posts_count: 31, votes_remaining: 105, votes_this_week: 0, comments_count: 367, ignore: false>

I'd like to add the .votes_cast property to the "a" variable:

我想将.votes_cast属性添加到“a”变量:

a.votes_cast = 5

But when I try to do this I get:

但当我尝试这样做时,我得到:

NoMethodError: undefined method `votes_casted=' for #<User:0x102c997f0>

What am I doing wrong?

我究竟做错了什么?

Thanks, Augusto

谢谢,奥古斯托

1 个解决方案

#1


10  

If this is to be a persistent property in your database then you should define a migration to add a column.

如果这是数据库中的持久属性,那么您应该定义迁移以添加列。

If it's just a temporary field in the User model then you can simply add an accessor to class User in app/models/user.rb.

如果它只是User模型中的临时字段,那么您只需在app / models / user.rb中为类User添加一个访问器。

class User < ActiveRecord::Base
  attr_accessor :votes_cast
end

#1


10  

If this is to be a persistent property in your database then you should define a migration to add a column.

如果这是数据库中的持久属性,那么您应该定义迁移以添加列。

If it's just a temporary field in the User model then you can simply add an accessor to class User in app/models/user.rb.

如果它只是User模型中的临时字段,那么您只需在app / models / user.rb中为类User添加一个访问器。

class User < ActiveRecord::Base
  attr_accessor :votes_cast
end