【问题标题】:Problem with has_many :through Association in Ruby on Railshas_many 的问题:通过 Ruby on Rails 中的关联
【发布时间】:2010-12-28 11:11:07
【问题描述】:

has_many 有问题:通过关联,我无法调用u1.UsersProfileAttributes.find_by_ProfileAttribute_name("icq") 方法,rails 表示该方法不存在。方法u1.UsersProfileAttributes.find_by_ProfileAttribute_id(3) 工作正常。 u1 是一个用户对象。我不知道是什么问题,因为我的联想似乎没问题。看看:

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

【问题讨论】:

    标签: ruby-on-rails methods associations has-many


    【解决方案1】:

    您需要查询 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 的属性。

    【讨论】:

    • 谢谢,没错。另一个问题:是否有一种简单的方法来创建或更改关系。我现在应该这样做:upa = UsersProfileAttribute?.new(:user => u, :ProfileAttribute? => pa, :value => "Profil Wert") u 是用户对象,pa 是 ProfileAttribute 对象。 1 行方法会很好,例如ProfileAttribute 是自动生成的还是类似的?
    • 另一个问题:如何更改特定用户的已知 ProfileAttribute 的值?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-14
    • 1970-01-01
    • 2012-06-12
    • 2011-01-13
    • 2011-04-21
    • 2012-04-01
    相关资源
    最近更新 更多