2011-12-18 32 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

相關問題