【问题标题】:Showing User Profile显示用户资料
【发布时间】:2016-04-15 09:28:48
【问题描述】:

我一直在努力解决这个问题,但几个小时后我终于迷路了。我正在尝试为用户创建个人资料。由于我拥有的用户的属性和类型,我将配置文件模型和用户模型分开。用户与配置文件具有 has_one 关系。我的问题似乎是我不仅对路线感到困惑,而且对配置文件的控制器也感到困惑。我只是希望能够有一个 link_to 来显示用户的个人资料。但是在代码上

user.rb

has_one  :profile
after_create :create_profile
def create_profile
  self.profile.create(:name => self.user_name)
end

轮廓模型

profile.rb
belongs_to :user, required: true, autosave: true

个人资料路线

resources :profile 

配置文件控制器

class ProfilesController < ApplicationController
  before_action :owned_profile, only: [:edit]
  before_action :get_profile
  layout "profile"
  respond_to :html, :js

  def show
    @activities = PublicActivity::Activity.where(owner:@user).order(created_at: :desc).paginate(page: params[:page], per_page: 10)
  end

  def followers
    @followers = @user.user_followers.paginate(page: params[:page])
  end

  def edit
  end

  def update
    if @profile.update(profile_params)
      flash[:notices] = ["Your profile was successfully updated"]
      render 'show'
    else
      flash[:notices] = ["Your profile could not be updated"]
      render 'edit'
    end
  end

  private

  def profile_params
    params.require(:profile).permit(:name, :cover)
  end

  def owned_profile
    unless current_user == @user
      flash[:alert] = "That profile doesn't belong to you!"
      redirect_to root_path
    end
  end

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

我完全不知道我需要做什么,我应该因为 after_create 方法而向用户的控制器添加一些东西吗?我的资源:配置文件应该在资源:用户下吗?

我尝试查看用户个人资料时遇到的错误是 Couldn't find Profile with 'id'=

我使用的link_to方法是&lt;%= link_to "View Profile", profiles_show_path(@user) %&gt;

请让我知道任何可能有帮助的事情,感谢您的时间和帮助。同样,由于用户类型不同以及我计划对配置文件建模的方式,我不想只将用户的“显示”显示为配置文件。

【问题讨论】:

  • 我为问题中的代码质量道歉
  • 根据你的路线(假设它实际上是resources :profiles)你应该有link_to "View Profile", profile_path(@user.profile)
  • @ChakreshwarSharma:是的,那个更好:)

标签: ruby-on-rails belongs-to user-profile has-one


【解决方案1】:

使用下面的代码:

<%= link_to "View Profile", @user.profile %>

【讨论】:

  • 完美谢谢!
猜你喜欢
  • 1970-01-01
  • 2019-11-29
  • 2012-04-24
  • 1970-01-01
  • 2013-05-12
  • 2016-06-26
  • 2019-06-30
  • 2021-03-09
  • 1970-01-01
相关资源
最近更新 更多