未在用户显示的属性#show page

时间:2013-12-21 00:49:48

标签: ruby-on-rails ruby-on-rails-4

users_controller.rb

class ProfilesController < ApplicationController
  before_filter :authenticate_user!

  def show
    @user = User.find(params[:id]) || User.find(current_user.id)
    @questions_for_about = @user.questions.for_about.order('id asc')
    @questions_for_personality = @user.questions.for_personality.order('id asc')
  end
end

用户#show.html.erb

   <div class="element">
          Ethinicity:
          <%= @user.ethnicity.present? ? @user.ethnicity.name : "" %>
        </div>
        <div class="element">
          Education:
          <span class="select_for_education">
           <%= @user.education.present? ? @user.education.name : "" %>
        </div>

user.education.name只显示以下内容 - 教育:

使用以下选项不显示用户在其个人资料中选择的教育:

  <div class="element">
          Ethinicity:
          <%= best_in_place current_user, :ethnicity_id, :type => :select, collection: Ethnicity.all.map{|e| [e.id, e.name]}, :inner_class => 'education-edit', nil: 'Select Ethnicity' %>
        </div>
        <div class="element">
          Education:
          <span class="select_for_education">
        <%= best_in_place current_user, :education_id, :type => :select, collection: Education.all.map{|e| [e.id, e.name]}, :inner_class => 'education-edit', nil: 'Select Education' %>
        </div>

我做错了什么?如何让用户在他/她自己的个人资料中显示的教育显示在节目页面中?

先谢谢!

User.rb

class User < ActiveRecord::Base
  include PgSearch

  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :omniauthable,
         :omniauth_providers => [:facebook, :twitter, :linkedin]

  attr_accessible :email, :password, :password_confirmation, :zip, :gender, :remember_me, :first_name, :last_name,
                  :birthday, :current_password, :occupation, :address, :interests, :aboutme, :profile_image,
                  :photos_attributes, :age, :education_id, :ethnicity_id, :blurb

  has_many :authorizations, :dependent => :destroy
  has_many :comments
  has_many :events
  has_many :photos, as: :attachable
  has_many :questions
  has_many :sent_messages, class_name: 'Message', foreign_key: :sender_id
  has_many :received_messages, class_name: 'Message', foreign_key: :receiver_id
  has_one  :ethnicity
  has_one  :education
end

ethnicity.rb

class Ethinicity < ActiveRecord::Base
  attr_accessible :name
  has_many :users
end

education.rb

class Education < ActiveRecord::Base
  attr_accessible :name
  has_many :users
end

1 个答案:

答案 0 :(得分:2)

您遗失了belongs_tohas_many关系的has_one关联。需要在其表具有外键的模型中定义belongs_to关联定义。

鉴于你的模型,虽然可以想象其他方式,但我认为这些关联应该是这样的:

# User Model
class User < ActiveRecord::Base
  ...
  belongs_to  :ethnicity
  belongs_to  :education
end

# Ethnicity Model
class Ethinicity < ActiveRecord::Base
  attr_accessible :name
  has_many :users
end

# Education Model
class Education < ActiveRecord::Base
  attr_accessible :name
  has_many :users
end