खोज…


रेल कंसोल के साथ तालिकाओं के साथ खेलना


टेबल देखें

ActiveRecord::Base.connection.tables

किसी भी तालिका को हटाएं ।

    ActiveRecord::Base.connection.drop_table("users")
    ------------OR----------------------
    ActiveRecord::Migration.drop_table(:users)
    ------------OR---------------------
    ActiveRecord::Base.connection.execute("drop table users")

मौजूदा कॉलम से इंडेक्स निकालें

 ActiveRecord::Migration.remove_index(:users, :name => 'index_users_on_country')

जहां country में users तालिका में पहले से जोड़े गए इंडेक्स के साथ माइग्रेशन फ़ाइल में एक कॉलम नाम है, जैसा कि नीचे दिखाया गया है: -

 t.string :country,add_index: true

विदेशी कुंजी की कमी को दूर करें

ActiveRecord::Base.connection.remove_foreign_key('food_items', 'menus')

जहां menus has_many food_items और उनके संबंधित माइग्रेशन भी हैं।

कॉलम जोड़ें

ActiveRecord::Migration.remove_column :table_name, :column_name

उदाहरण के लिए:-

 ActiveRecord::Migration.add_column :profiles, :profile_likes, :integer, :default => 0

रेल के तरीके - बूलियन मान वापस करना

रेल मॉडल में कोई भी विधि बूलियन मान वापस कर सकती है।

सरल विधि-

  ##this method return ActiveRecord::Relation
  def check_if_user_profile_is_complete
    User.includes( :profile_pictures,:address,:contact_detail).where("user.id = ?",self)
  end

फिर से सरल विधि बूलियन मान लौटाते हुए-

  ##this method return Boolean(NOTE THE !! signs before result)
  def check_if_user_profile_is_complete
    !!User.includes( :profile_pictures,:address,:contact_detail).where("user.id = ?",self)
  end

तो, वही विधि अब कुछ और के बजाय बूलियन लौटेगी :)।

त्रुटि को संभालना - अपरिभाषित विधि `जहां 'के लिए #

कभी कभी हम एक का उपयोग करना चाहते where अभिलेखों का आ संग्रह पर क्वेरी लौटे जो नहीं है ActiveRecord::Relation .Hence हम ऊपर त्रुटि मिलती है के रूप में Where खंड के पता है ActiveRecord और के लिए नहीं Array ।

Joins का उपयोग करके इसके लिए एक सटीक समाधान है।

उदाहरण : -

मान लें कि मुझे सभी उपयोगकर्ता प्रोफ़ाइल (UserProfile) ढूंढने की आवश्यकता है जो सक्रिय हैं जो एक id (10) वाला उपयोगकर्ता (उपयोगकर्ता) नहीं है।

UserProfiles.includes(:user=>:profile_pictures]).where(:active=>true).map(&:user).where.not(:id=>10)

के बाद तो ऊपर क्वेरी असफल हो जायेगी map के रूप में map एक वापस आ जाएगी array जो साथ काम नहीं करेंगे where खंड।

लेकिन जॉन्स का उपयोग करने से, यह काम करेगा,

UserProfiles.includes(:user=>:profile_pictures]).where(:active=>true).joins(:user).where.not(:id=>10)

जैसे-जैसे map समान रिकॉर्ड joins जाएंगे, वैसे-वैसे वे ActiveRecord होंगे न कि Array ।



Modified text is an extract of the original Stack Overflow Documentation
के तहत लाइसेंस प्राप्त है CC BY-SA 3.0
से संबद्ध नहीं है Stack Overflow