2009-12-20 2 views
0

У меня проблема с has_many: через ассоциацию, я не могу вызвать метод u1.UsersProfileAttributes.find_by_ProfileAttribute_name("icq"), рельсы означают, что этот метод не существует. Метод 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_id является атрибутом UsersProfileAttribute ... так ActiveRecord строит вам динамический искатель.

u1.UsersProfileAttributes.find_by_ProfileAttribute_name("icq") не работает, потому что ProfileAttribute_name не является атрибутом UsersProfileAttribute.

+0

Спасибо, это правильно. Другой Questioen: Есть простой метод создания или изменения релиза. Id делает это так: upa = UsersProfileAttribute? .new (: user => u,: ProfileAttribute? => Pa,: value => "Profil Wert") u - пользовательский объект, а pa - объект ProfileAttribute. Метод 1 линии был бы хорошим, например. что ProfileAttribute генерируется автоматически или что-то в этом роде? – LeonS

+0

Другой вопрос: как я могу изменить значение известного атрибута ProfileAttribute для конкретного пользователя? – LeonS

Смежные вопросы