2015-03-31 104 views
0

用戶有一個配置文件。配置文件屬於用戶。查詢似乎在postgres中工作,但我無法讓關聯在視圖中正常工作。下面是查詢結果:爲什麼我的連接不工作?

User Load (0.4ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC 
    User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = 5 ORDER BY "users"."id" ASC LIMIT 1 
    Profile Load (0.3ms) SELECT "profiles".* FROM "profiles" WHERE "profiles"."user_id" = $1 LIMIT 1 [["user_id", 5]] 

下面是用戶配置文件中的兩個模式:

用戶:

class User < ActiveRecord::Base 

    devise :database_authenticatable, :registerable, 
    :recoverable, :rememberable, :trackable, :validatable, :confirmable 

    has_one :profile, dependent: :destroy 

    accepts_nested_attributes_for :profile, allow_destroy: true 

end 

簡介:

class Profile < ActiveRecord::Base 

    belongs_to :user, polymorphic: true 

end 

的控制器...

用戶:

class UsersController < ApplicationController 

    def index 
     @profiles = Profile.all 
     @users = User.all.order(:id) 
     User.joins(:profile) 
    end 

    private 
     def set_user 
     @user = User.find(params[:id]) 
     end 

end 

簡介:

class ProfilesController < ApplicationController 
    before_action :set_profile, only: [:show, :edit, :update, :destroy] 

    # GET /profiles 
    # GET /profiles.json 
    def index 
     @profiles = Profile.all 
    end 

    # GET /profiles/1 
    # GET /profiles/1.json 
    def show 
    end 

    # GET /profiles/new 
    def new 
     @profile = Profile.new 
    end 

    # POST /profiles 
    # POST /profiles.json 
    def create 
     @profile = Profile.new(profile_params) 

     respond_to do |format| 
     if @profile.save 
      format.html { redirect_to @profile, notice: 'Profile was successfully created.' } 
      format.json { render :show, status: :created, location: @profile } 
     else 
      format.html { render :new } 
      format.json { render json: @profile.errors, status: :unprocessable_entity } 
     end 
     end 
    end 

private 

    def set_profile 
     @profile = Profile.find(params[:id]) 
    end 

    def profile_params 
     params.require(:profile).permit(:user_id) 
    end 

最後在/用戶/索引視圖:

<%= user.profile.user_id %> 

但是當我嘗試呈現視圖,我收到以下錯誤:

undefi ned方法`user_id'爲零:NilClass

我感謝任何幫助。

回答

1

如果你確實不需要關聯是多態的,那麼你應該從Profile模型中刪除它。

class Profile < ActiveRecord::Base 

    belongs_to :user 
end 

但是,如果你需要的關聯是多態的,那麼你需要改變User模型。

class User < ActiveRecord::Base 

    devise :database_authenticatable, :registerable, 
    :recoverable, :rememberable, :trackable, :validatable, :confirmable 

    has_one :profile, 
     dependent: :destroy, 
     as: user 

    accepts_nested_attributes_for :profile, allow_destroy: true 

end 

,你也需要在你的Profile模型添加user_type