簡體   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