在Ruby on Rails中建立Has_Many through關係有各種參考,但關於如何處理關係的信息很少。有很多關係
我有以下變量一個用戶表:
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.string "confirmation_token"
t.datetime "confirmed_at"
t.datetime "confirmation_sent_at"
t.string "unconfirmed_email"
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
然後,我有一個維基表:
t.string "title"
t.datetime "published_at"
t.datetime "created_at"
t.datetime "updated_at"
t.text "body"
而且,我有一個關係表中加入二:
t.integer "wiki_id"
t.integer "user_id"
t.boolean "creator_created"
t.boolean "collaborator"
關係類屬於其他類中的每一個:
belongs_to :users
belongs_to :wikis
其它兩個具有的has_many,通過代碼:
class User < ActiveRecord::Base
has_many :relationships
has_many :wikis, through: :relationships
,反之亦然。
所以我的問題是,現在是什麼?我怎樣才能調用這些不同的類和它們的變量? user.wiki似乎不起作用,或user.relationship.wiki;即使relationship.created_creator也會提取錯誤信息!
特別是,我希望能夠找出用戶是否創建了一個wiki,以便該用戶可以編輯該wiki。我試着在用戶模式來創建一個方法是:
def creator?(wiki, user)
Relationship.where(wiki_id: wiki.id, user_id:user.id).creator_created
end
當我把它從一個政策文件,我得到的錯誤:
undefined method `creator_created' for # <ActiveRecord::Relation::ActiveRecord_Relation_Relationship:0xbb19b84>
誰能幫助我用我的has_many ,通過關係?我如何可以參考與用戶相關的wiki,或與兩者相關的creator_created字段?
謝謝!
謝謝!不幸的是,我仍然收到錯誤「未初始化的常量User :: Wiki」。在Rails控制檯中,我爲用戶(調用'User.connection'建立連接):Class「得到錯誤」NoMethodError:undefined method'wikis'。有任何想法嗎? –
我意識到我沒有指定一個用戶,但即使當我(User.last),我得到了錯誤「NameError:未初始化的常量User :: Wiki」 –
你是如此接近:)請參閱我的編輯。 Rails中的整個複數/單數業務非常隨意。一旦你瞭解了慣例,它將成爲第二天性。 – zetetic