2011-12-18 78 views
2

我想作这样的事:导轨 - 如何将对象添加到一个变量

@profiles 
#(I think in Java, so I have declared an @profiles variable there! I know it's probably wrong!) 
@users.each do |user| 
    profile = Profile.find(params[user.id]) 
    @profiles.add(profile) 
end 

的用户配置文件中有一个一对一的关系。

用户配置文件, 轮廓属于用户

+1

你还没有“声明”一个'@ profiles'变量存在。你只是试图查找那个实例变量,并且因为它不存在,所以该行的计算结果为'nil'。 – d11wtq 2011-12-18 04:32:59

回答

5

您需要初始化数组。


@profiles = [] 
@users.each do |user| 
    profile = Profile.find(params[user.id]) 
    @profiles << profile if profile 
end 

如果你有关系,你应该能够只是说:


@profiles = [] 
@users.each do |user| 
    profile = user.profile 
    @profiles << profile if profile 
end 
+0

d11wtq感谢编辑:) – daniel 2011-12-18 19:14:30

0

只要做到以下几点:

更换

@profiles.add(profile) 

@profiles << profile 

的< <运营商添加的元素在右边e数组在左边。

+0

我试过了,但它在@profiles上给出了一个.nil错误 – spuriosity 2011-12-18 01:25:37

+0

请看下面,你需要首先初始化@profile – daniel 2011-12-18 02:21:25

1

find将已经返回一个集合。

在这种情况下,然而,它看起来更像你应该有一个成文的关系:

class User 
    has_one :profile 
end 

class Profile 
    belongs_to :user 
end 

信息:has_onebelongs_to

+0

,这正是我所拥有的,并且我试图获取基于集合的配置文件集合user.id所在用户标识的位置.user_id – spuriosity 2011-12-18 00:56:14

+0

@spuriosity如果这就是你的,为什么你没有显示它?你如何保存用户的个人资料?为什么您在Rails免费赠送给您时重新建立关联? – 2011-12-18 00:57:26

+0

我正在使用where('user_id LIKE?',“%#{search}%”)来搜索(在配置文件obj中),但这显然是在配置文件表中搜索id。我需要搜索与配置文件关联的用户表,而不是通过配置文件表。试图找出解决方法。 – spuriosity 2011-12-18 01:01:13

1

如果你有这个在你的模型

class User 
    has_one :profile 
end 

class Profile 
    belongs_to :user 
end 

而这在你的个人资料迁移

t.integer :user_id 

你可以找到这样

@profiles = Profile.all 

,然后配置文件在你的意见

<% @profiles.each do |profile| %> 

<%= profile.user.name %> 

<%end%> 

更新

如果你有

在哪里('USER_ID样的? ',“%#{search}%”)

试试这个模型/ user.rb。

def self.search(search) 
    if search 
     where('name LIKE ? ', "%#{search}%") 
    else 
     scoped 
    end 
end 

在控制器:

@users = User.search(PARAMS [:搜索])

,然后在你的意见

<% @users.each do |user| %> 

<%= user.profile.name %> 

<%end%> 

A Guide to Active Record Associations

+0

我有这样的:where('user_id LIKE?',“%#{search}%”),我需要的是搜索user_id – spuriosity 2011-12-18 00:58:27

+0

处的用户的.name属性,我对答案进行了更新。我明天再仔细看看 – 2011-12-18 01:26:05