2012-03-01 41 views
0

我對Ruby非常新(2-3天),並在現有的數據庫上使用它。我有一個用戶表(以前建在Joomla),並設法使其工作(以及登錄和註銷),但我需要約束另一個模型,即'引導'給用戶已登錄。紅寶石在軌道上,設計和使用用戶來限制現有的模型

我已經能夠獲得所有當前'潛在客戶'輸出並使用CRUD操作,但是我想知道如何根據登錄用戶限制數據。

'潛在客戶'模型是使用腳手架和'set_table_name'和'set_primary_key'屬性已被覆蓋。我還添加

belongs_to :user, :class_name => "user", :foreign_key => "leadid"

到模型。

「用戶」模式如下

class User < ActiveRecord::Base 
# Include default devise modules. Others available are: 
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and  :omniauthable 
`establish_connection :web_development 
set_table_name "users" 
set_primary_key "id" 

has_many :leads, 
     :class_name => "Lead", 
     :foreign_key => "LeadID" 

devise :database_authenticatable, :registerable, 
    :recoverable, :rememberable, :validatable 

# Setup accessible (or protected) attributes for your model 
attr_accessible :email, :password, :password_confirmation, :remember_me 

    alias :devise_valid_password? :valid_password? 
    def valid_password?(password) 
    return true (temp to bypass the password) 
    end 
end 

非常感謝 魯迪

回答

0

Devise通過current_user爲當前登錄用戶提供訪問者。因爲它看起來像你的關係設置正確,如果你想爲只顯示已登錄的用戶在控制器的索引行爲的線索,你只需要這樣:

def index 
    @leads = current_user.leads 
end 
+0

將試一試並報告回來,看起來像它會工作。非常感謝 – Dudedolf 2012-03-01 19:24:17

+0

我做了更改,我可以從控制檯輸出中看到它正在查詢引線表。然而,不幸的是,我的用戶字段不是通過'id'主鍵而是通過'userid'字段'加入'我的'潛在客戶'表。即User.UserID加入到Lead.UserID,而不是User.ID加入Lead.ID.看看網頁,但無法找到如何覆蓋該字段。再次感謝 – Dudedolf 2012-03-01 20:30:00

+0

聽起來你只需要在Lead模型中更新你的belongs_to。因此,在Lead.rb中,將關係更改爲'belongs_to:user,:primary_key =>「UserID」' – wpgreenway 2012-03-01 20:36:30

0

您可以將此行添加到您的leads_controller

before_filter :authenticate_user! 

這應該採取的確保護理用戶在允許訪問該控制器中的任何操作之前已被正確認證。

+0

感謝有用的技巧,那將是非常有用的 – Dudedolf 2012-03-01 19:23:38