开发者

Associations in Rails

开发者 https://www.devze.com 2023-02-01 11:18 出处:网络
i am new to Rails .. i am having a Table named users (id,name) and another table which has the additional information of the usercalled

i am new to Rails .. i am having a Table named users (id,name) and another table which has the additional information of the user called user_details(id,user_id,additional_info) where additional_info is a hash .

In the User Model i added a line

has_one :user_details

And in the User_Detail model i added a line

belongs_to :user
serialize :additional_details, Hash

Now in the Users Controller i am having an action

# set_user_empid to set the hash value empid in the additi开发者_运维知识库onal_info column for the current_user
    def set_user_empid  
           @user1 = current_user
           @user_detail1=@user1.user_details
           @user_detail1.additional_details[:empid] = params[:value]
           @user_detail1.save
           render :text => CGI::escapeHTML(@user_detail1.additional_details[:empid].to_s)

    end 

The above one @user1.user_details shows me the error as

NameError (uninitialized constant User::UserDetails):

But the same thing if i change the has_one to has_many i am getting the actual result...

Please give suggestions...


The quick fix here is to change has_one :user_details to has_one :user_detail, but really what you want is to get rid of the UserDetail model entirely and just move the column into the User model, so the users table has these columns: id, name, additional_info and then move the call to serialize into the User model. No real reason to have a separate table just for metadata.


I believe since you are using user_details, pluralized, it is not able to pick it up. Could you try using has_one :user_detail

0

精彩评论

暂无评论...
验证码 换一张
取 消