#ruby-on-rails #ruby-on-rails-4 #model-associations #belongs-to #has-one
#ruby-on-rails #ruby-on-rails-4 #модель-ассоциации #принадлежит #имеет-один
Вопрос:
У меня есть 2 модели:
Модель пользователя и модель профиля.
Моя ассоциация заключается в следующем:
Class User < ActiveRecord::Base
has_one :profile
end
Class Profile < ActiveRecord::Base
belongs_to :user
validates user_id, presence: true
end
Мои контроллеры выглядят следующим образом:
ПОЛЬЗОВАТЕЛЬ:
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
if logged_in?
@micropost = current_user.microposts.build
@profile = current_user.build_profile
@new_comment = Comment.build_from(@user, current_user.id, ' ')
end
@microposts = @user.microposts.paginate(page: params[:page])
@profile_player = @user.profile
end
end
Профиль:
class ProfilesController < ApplicationController
before_action :logged_in_user, only: [:create, :destroy]
before_action :correct_user, only: [:destroy]
def create
@profile = current_user.build_profile(profile_params)
if @profile.save
flash[:success] = 'Profile Has Been Published'
# redirect_to request.referrer || root_url
redirect_to users_url
else
render :'pages/home'
end
end
def update
@profile.update(profile_params)
redirect_to user_url
end
def destroy
end
private
def profile_params
params.require(:profile).permit(:name, :age, :nationality, :country, :city, :height, :weight,
:dominant_hand, :play_position, :highschool, :college, :team,
:awards, :highlights)
end
def correct_user
@profile = current_user.profile.find_by(id: params[:id])
redirect_to root_url if @profile.nil?
end
end
Теперь то, что я пытаюсь сделать, это частично отобразить представление профиля на странице показа пользователя (следуя руководству Майкла Хартла):
следовательно, я визуализирую представление через переменную экземпляра, которую я создал в Users Controller show action для profile:
def show
#@username = params[:id] ==============> this is intended to show the user name instead
# of the user id in the address bar
@user = User.find(params[:id])
if logged_in?
@micropost = current_user.microposts.build
@profile = current_user.build_profile
@new_comment = Comment.build_from(@user, current_user.id, ' ')
end
@microposts = @user.microposts.paginate(page: params[:page])
@profile_player = @user.profile
end
итак, на моей странице показа пользователя:
Я визуализирую вид профиля следующим образом:
Теперь вот ошибка, с которой я сталкиваюсь, мой профиль сохраняется правильно при отправке формы, однако, когда я возвращаюсь на страницу показа пользователя (я отображаю форму профиля на домашней странице пользователя) для просмотра профиля, я получаю сообщение об ошибке:
'nil' is not an ActiveModel-compatible object. It must implement :to_partial_path.
<div class="current-user-persona">
<%= render @profile_player %> =====> highlighted section for error
</div>
Я не уверен, что я здесь делаю не так, вы можете мне помочь?
смотрел на это в течение нескольких дней.
Комментарии:
1. Я не уверен, но думаю, что в ваших параметрах у вас нет
:id
, может быть, у вас есть:user_id
.. Взгляните на информацию об отладке, вы увидите, какие параметры у вас есть.2. параметры:user_id
3. в любом случае, значение profile_player instance_variable, скорее всего, равно нулю, даже если это не так, поскольку вы рендерите частичное напрямую, оно будет отображаться в app /views/profiles/_profile.html.erb, если класс для @user.profile равен «Profile»
4. @JeremyDeey итак, в вашем действии show вы должны сделать
@user = User.find(params[:user_id])
вместо@user = User.find(params[:id])
5. @nobilik это не сработало