【问题标题】:Rails - Show Action & View for models with one-to-one association?Rails - 为具有一对一关联的模型显示操作和视图?
【发布时间】:2013-04-24 05:02:29
【问题描述】:

我有一个带有用户模型和 Instructor_Profile 模型的简单应用程序。这两个模型之间的关联是一对一的。我无法让我的视图 show.html.erb 呈现。我只是想显示 Instructor_Profile 模型中的单个属性,但出现此错误:

Instructor_profiles#show 中的 NoMethodError nil:NilClass 的未定义方法“名称”

任何帮助将不胜感激!

Models:

class User
has_one :instructor_profile

class InstructorProfile
belongs_to :user


UsersController:

def new
  @user = User.new
end


def create
  @user = User.new(params[:user])
  if @user.save
    UserMailer.welcome_email(@user).deliver
    render 'static_pages/congratulations'
  else
    render 'new'
  end
end



InstructorProfilesController:

def new
  @instructor_profile = current_user.build_instructor_profile
end


def create
  @instructor_profile = current_user.build_instructor_profile(params[:instructor_profile])
  if @instructor_profile.save
    flash[:success] = "Profile created!"
    redirect_to root_path
  else
  ....
  end
end


def show
  @user = User.find(params[:id])
  @instructor_profile = @user.instructor_profile
end



Views/instructor_profiles/show.html.erb:

<p>Display Name: <%= @user.instructor_profile.name %></p> 

【问题讨论】:

  • 你试过@instructor_profile.name 吗?
  • 嗨,索尼。是的,我也试过了。结果相同。

标签: ruby-on-rails-3 model-view-controller


【解决方案1】:

这是因为@user.instructor_profilenil。 这意味着没有与@user 对应的instructor_profile。 请检查UserController 中的create 方法以确认instructor_profile 是否正在创建。代码应该是这样的,

@user.instructor_profile = InstructorProfile.new(name: "my_name")
@user.instructor_profile.save

编辑:

has_one 关联并不意味着每个用户都必须有一个讲师档案。因此,在您拨打@user.instructor_profile.name 之前,只需确认@user 是否有instructor_profile。在您看来,您可以通过添加一个条件轻松解决此错误..

&lt;p&gt;Display Name: &lt;%= @user.instructor_profile ? @user.instructor_profile.name : "no instructor_profile present" %&gt;&lt;/p&gt;

还有一点,在instructor_profiles_controller/show,把代码改成

@instructor_profile = InstructorProfile.find(params[:id])
 @user = @instructor_profile.user

【讨论】:

  • 嗨,塔哈。我认为你对这个问题是正确的。但是,我不确定为什么我必须在 UsersController 中定义任何关于讲师配置文件的内容。也许我不完全了解 has_one 关联。但我认为仅仅因为用户有一个讲师个人资料,并不意味着每个用户都必须有一个讲师个人资料。这不准确吗?
  • 此外,我刚刚为这两个控制器添加了新的 & create 操作供您查看。谢谢!
  • 谢谢塔哈!对 InstructorProfilesController 中显示操作的调整解决了这个问题。我也会在我的观点中添加条件。非常感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-24
  • 1970-01-01
  • 2013-03-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多