我有三種模型。指定有很多通過關聯的列導軌
User
has_many :boards through => :celebrations
has_many :celebrations, :dependent => :destroy
Board
has_many :celebrations, :dependent => :destroy
has_many :users, :through => :celebrations do
def by_role(role)
find(:all, :conditions => ["celebrations.role = ?", role])
end
end
Celebration
:belongs_to :user
:belongs_to :board
慶典表
create_table :celebrations do |t|
t.column :board_id, :int, :null => false
t.column :user_id, :int, :null => false
t.column :role, :string, :null => false
t.column :token, :string
t.column :accepted, :boolean, :default => false
t.timestamps
在控制器:
@board = Board.find(session[:board_id])
@friends = @board.users.by_role("FRIEND")
在視圖:
<% for friend in @friends do %>
<%= friend.name %>
<%= friend.email %>
然而,當我執行以下操作:
<% friend.celebration.accepted %>
我得到以下錯誤:
undefined method `celebration' for #<User:0x104788c00>
我如何可以訪問的慶祝活動表「接受」列返回隨着使用模型擴展「by_role(角色)」的記載。
非常感謝您的幫助。
什麼是用戶和慶祝活動之間的關聯。 'has_many'或'has_one'。你沒有在你的代碼中提到它。我認爲它是'has_many',所以你應該調用'friend.celebrations'並根據你的需要調用'friend.celebrations.first.accepted'或者其他什麼。 – rubyprince 2011-03-21 06:12:26
與@rubyprince一致,你正在與用戶(朋友)對象交談,就好像它是關係中的多對一方一樣,但它確實是一對多的一面。 – 2011-03-21 06:38:28
我的appologies。我忘記了關係。我想我試圖避免另一個數據庫命中並應用急切的加載。我希望有一個查詢將返回來自Users表和來自慶典表的'accepted'列的所有數據。然後以friend.celebrations.accepted的身份訪問信息。有沒有辦法做到這一點使用急切加載? – chell 2011-03-21 08:19:13