[英]Rails pass value to associated model
I'm trying to make a association that automatically get the name of the object. 我正在尝试建立一个自动获取对象名称的关联。 for exemple 举个例子
**User has one Brand**
User Table:
id
Name
=================
**Belongs to User**
Brand Table:
id
user_id
user_name
So i would like to know how to pass the user name to the brand table, thank's 所以我想知道如何将用户名传递给品牌表,谢谢
Just define a method: 只需定义一个方法:
class Brand < ActiveRecord::Base
belongs_to :user
def user_name
user.name
end
end
b = Brand.first
name = b.user.name
Its not really necessary to have that extra user name column in your database. 确实没有必要在数据库中包含该额外的用户名列。
You can simply do brand.user.name to get the user's name. 您只需执行brand.user.name即可获取用户名。
so if your view has an instance of @brand you would simply do @brand.user.name 因此,如果您的视图具有@brand实例,则只需执行@ brand.user.name
Otherwise do as meagar said. 否则,如米加尔所说。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.