2009-12-20 88 views
0

我has_many有一個問題:通過關聯,我不能調用u1.UsersProfileAttributes.find_by_ProfileAttribute_name("icq")方法,rails表示這個方法不存在。方法u1.UsersProfileAttributes.find_by_ProfileAttribute_id(3)正常工作。 u1是一個用戶對象。我不知道最新的問題,因爲我的協會似乎沒問題。看一看:問題has_many:通過Ruby on Rails中的關聯

class ProfileAttribute < ActiveRecord::Base 
    has_many :UsersProfileAttributes 
    has_many :users, :through => :UsersProfileAttributes 
end 
class User < ActiveRecord::Base 
    has_many :UsersProfileAttributes 
    has_many :ProfileAttributes, :through => :UsersProfileAttributes 
end 
class UsersProfileAttribute < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :ProfileAttribute 
end 

我的移民文件:

class CreateProfileAttributes < ActiveRecord::Migration 
     def self.up 
     create_table :profile_attributes do |t| 
      t.string :name 
      t.integer :profile_group_id 
      t.timestamps 
     end 
    create_table :users_profile_attributes do |t| 
     t.integer :user_id 
     t.integer :ProfileAttribute_id 
     t.string :value 
    end 
    end 
    def self.down 
    drop_table :profile_attributes 
    drop_table :users_profile_attributes 
    end 
end 

回答

2

您需要查詢ProfileAttributes,不UsersProfileAttributes。這應該爲你工作:u1.ProfileAttributes.find_by_name('icq')

u1.UsersProfileAttributes.find_by_ProfileAttribute_id(3)工作,因爲ProfileAttribute_idUsersProfileAttribute的一個屬性...所以ActiveRecord爲您建立一個動態的發現者。

u1.UsersProfileAttributes.find_by_ProfileAttribute_name("icq")不起作用,因爲ProfileAttribute_name不是UsersProfileAttribute的屬性。

+0

謝謝,這就對了。 另一個問題:是否有一種簡單的方法來創建或改變這種關係。 Id現在這樣做:upa = UsersProfileAttribute?.new(:user => u,:ProfileAttribute?=> pa,:value =>「Profil Wert」) u是一個用戶對象,pa是一個ProfileAttribute對象。 1行方法是很好的,例如ProfileAttribute是自動生成的還是類似的東西? – LeonS 2009-12-20 19:51:14

+0

另一個問題:如何爲特定用戶更改已知ProfileAttribute的值? – LeonS 2009-12-20 20:02:09

相關問題