0

我想从我的个人资料模型belongs_to:user“用户模型”中访问“个人资料”表。如何在rails上访问Profiler模型insider users_controller?

首先在users_controller的show操作中,我想从配置文件表中获取数据以显示在用户配置文件页面上。

其次我想让用户可以使用表单编辑这些东西。我知道这是在更新操作中完成的?而编辑动作能够显示编辑视图页面上的表单..

这里是我的控制器:

class UsersController < ApplicationController 



    def new 
    @user = User.new 
    @title = "Practice" 
    end 

    def create 
    @user = User.new(params[:user]) 
    respond_to do |format| 
     if @user.save 
     @user.build_profile.save #same as Profile.new(:user_id => @user.id) 
     login @user 
     UserMailer.join_confirmation(@user).deliver 
     format.js { render :js => "window.location = '#{root_path}'" } 
     flash[:notice] = "Welcome!" 
     else 

     format.js { render :form_errors } 
     end 
    end 
    end 

    def show 

    end 

    def update 

    end 

    def edit 

    end 



end 

1)我将如何访问我的个人资料表? 用户has_one:个人资料 个人资料belongs_to:用户

建议将不胜感激。花了我半天的时间来弄清楚如何在profile表中创建一个对应于新创建用户的行,现在下一步是能够从我的users_controller中的模型中获取数据。我知道我可以创建一个profiles_controller并在那里做事情,但我现在不想尝试,因为我确定有一种方法可以通过users_controller来完成。

在此先感谢您给出的建议。

查看:

<%= @profile_data.first_name %> 

<h4><%= current_user.username.capitalize %></h4> 
<%= gravatar_image_tag(current_user.email, :alt => @title, :class => "gravatar", :gravatar => { :size => 150 }) %> 
<br /> 

试图通过users_controller从曲线表拉FIRST_NAME

def show 
    @user = User.find_by_username(params[:username]) 
    @profile_data = @user.profile 

    end 

路线:

match ':username' => "users#show" 

我希望看到的名字存储在first_name列配置文件表,当我访问本地主机:3000 /用户名

它不显示用户的名字。

回答

2

你可以这样做:

@user.profile 

,将返回属于用户

否则个人资料:

Profile.where('whatever condition you fancy') 

将返回基于条件的一个配置文件对象

+0

我得到这个错误:未定义的方法'档案'为零:NilClass – LondonGuy 2012-01-05 23:19:47

+0

这意味着用户是空的。你需要填充它。可能使用像这样的东西:@user = User.find(params [:id]),但不能告诉你更多没有看到路线和你正在运行什么行动 – Yule 2012-01-05 23:21:59

+0

我有个人资料表中的一些数据。我有一个用户配置文件在localhost:3000 /用户名,这里是“匹配”的路线:username'=>“users#show”“现在我想要做的是让用户的数据显示在用户页面上时我访问它。所以在show view中,我有@ variable_set_in_controller.first_name来查看它是否可以获取名字。在演出中,我尝试了一切,但仍然没有运气。我只是希望能够从配置文件表格/配置文件模型中获取信息到users_controller的show动作中。 – LondonGuy 2012-01-06 00:36:02

0

您需要在用户模型上使用has_one:profile,在配置文件模型上输入belongs_to:user,确保在配置文件表中具有相应的user_id列。将accepts_nested_attributes_for:profile添加到用户模型,然后您可以创建/编辑用户的配置文件以相同的形式编辑用户。

在轨道上阅读release notes on nested attributes和指南:associationsforms

+0

没有运气,我试图在show动作中使用用户名查找,但由于某种原因,我的日志告诉我它正在寻找“favicon”作为用户名。没有意义。 – LondonGuy 2012-01-06 12:55:05