2013-02-23 44 views
0

我發現了一些關於這個的帖子,但是我沒有嘗試過使用它,但迄今爲止我已經完成了它。對於rails我還是很新鮮 - 基本上我已經使用HTML和CSS,但是我接受了Skillshare Rails類,並且正在將它與Railstutorial書籍結合起來。所以請溫柔。在rails中顯示相關的數據(user_id,email等)

我有一個基本的應用程序,用戶可以創建'項目'。我用腳手架來取得'物品'。他們可能是微博。但隨着腳手架創建的觀點,我想顯示用戶的電子郵件地址,而不是電子郵件地址。我會在模型,視圖和控制器中更改哪些內容?這是我得到的。

控制器:

def email 
    @email = @item.user_id.email 
end 

視圖:

<td><%= item.content %></td> 
<td><%= @email %></td> 
<td><%= link_to 'Show', item %></td> 
<td><%= link_to 'Edit', edit_item_path(item) %></td> 
<td><%= link_to 'Destroy', item, confirm: 'Are you sure?', method: :delete %></td> 

產品型號:

class Item < ActiveRecord::Base 
    attr_accessible :content, :user_id 
    validates :content, :length => { :maximum => 140 } 
    belongs_to :user 
end 

用戶模型:

class User < ActiveRecord::Base 
    # Include default devise modules. Others available are: 
    # :token_authenticatable, :confirmable, 
    # :lockable, :timeoutable and :omniauthable 
    devise :database_authenticatable, :registerable, 
    :recoverable, :rememberable, :trackable, :validatable 

    # Setup accessible (or protected) attributes for your model 
    attr_accessible :email, :password, :password_confirmation, :remember_me 
    has_many :items 
end 
+0

我覺得你想'@email = @ item.user.email',因爲你不能得到'user_id'的電子郵件 – 2013-02-23 02:18:59

回答

1

有三種方法。

首先, 我覺得最好的方式。根據你的要求是簡單的授權。

class Item < ActiveRecord::Base 
    attr_accessible :content, :user_id 
    validates :content, :length => { :maximum => 140 } 
    belongs_to :user 

    delegate :email, to: :user 
end 

在視圖中,

要獲取。

<td><%= item.email %></td> 

像@cluster說

您可以在控制器使用

@email = @item.user.email 

或者

代碼移到產品型號

class Item < ActiveRecord::Base 
    attr_accessible :content, :user_id 
    validates :content, :length => { :maximum => 140 } 
    belongs_to :user 

    def user_email 
    user.email 
    end 
end 

在視圖中,

<td><%= item.user_email %></td> 
+0

這非常有幫助!非常感謝! – momchenr 2013-02-24 23:30:12

+0

如果您發現它確實有幫助,那麼您應該接受。 – 2013-02-25 07:24:17

0

在您的控制器中,您不想添加其他方法,因爲這些方法是用戶應該能夠通過URL訪問的「操作」。 (有些情況下,例如過濾器之前,但這超出了範圍)。

你可以在你的控制器動作

class ItemsController 
    def show 
    @item = Item.find params[:id] 
    @email = @item.user.email 
    end 
end 

做到這一點,或者你可以簡單地調用視圖本身@item.user.email