繁体   English   中英

has_many问题:通过Ruby on Rails中的关联

[英]Problem with has_many :through Association in Ruby on Rails

我遇到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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM