访问在Rails的链接模型的属性 [英] Accessing an attribute of a linked model in Rails

查看:155
本文介绍了访问在Rails的链接模型的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

那么,对不起,如果这不遇到连贯......我不知道我的所有的Ruby / Rails的术语(还)。

So, sorry if this doesn't come across coherently... I don't know all my Ruby / Rails terminology (yet).

我有一个名为个人资料和一个名为用户模式的模型,以及两个链接是这样的:

I have a model called "Profile" and a model called "User, and the two are linked like this:

class Profile < ActiveRecord::Base
belongs_to :user
class User < ActiveRecord::Base
has_one :profile

现在,在索引和秀的观点轮廓,我做的,我希望能够从用户模式访问属性名。我怎样才能做到这一点?我想我需要的东西,看起来像这样的控制器:

Now, in the "index" and "show" views of profiles that I made, I want to be able to access the attribute "name" from the User model. How can I do this? I imagine I'll need something in the controller that looks like this:

class ProfilesController < ApplicationController
  def show
    @user = User.find(params[:user_id])

然后访问它在这样的观点:

And then access it in the view like this:

<%= @user.name %>

但是,code,它位在那里不起作用。

But that bit of code right there doesn't work.

感谢您的帮助。

推荐答案

如果属性名称属于个人资料的模式,在你看来

If the attribute name belongs to the Profile model, in your view:

<%= @user.profile.name %>


如果属性名称属于用户模式,请停止服务器,运行耙分贝:迁移,以确保每一个移民已应用到你的数据库;然后运行轨控制台 Ruby脚本/控制台来检查attribe正在为你的模型:


If the attribute name belongs to the User model, please stop the server, run rake db:migrate to be sure every migration has been applied to your database; then run rails console or ruby script/console to check if the attribe is working for your model:

> u = User.first
> u.name

如果最后一个命令返回一个空字符串或您的第一个用户名,一切工作正常。如果你得到一个 NoMethodError:未定义的方法,你应该检查你的数据库应该处理的名称的列属性可能是失踪了。

If the last command returns an empty string or the name of your first user, everything is working. If you get a NoMethodError: undefined method you should check your database as the column that should handle the name attribute is probably missing.

这篇关于访问在Rails的链接模型的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆