2012-12-09 37 views
0

對於用戶有藍圖的每個項目,我想顯示項目名稱和鏈接到project_path。謝謝。Ruby on Rails,如何使用has_many名稱向users/show.html.erb添加項目:through blueprints

這些都是我Ac​​tiveRecords

class User < ActiveRecord::Base 
    attr_accessible :id, :name 
    has_many :blueprints 
    has_many :projects, :through => :blueprints 
end 

class Project < ActiveRecord::Base 
    attr_accessible :id, :name 
    has_many :blueprints 
    has_many :users, :through => :blueprints 
end 

class Blueprint < ActiveRecord::Base 
    attr_accessible :id, :name, :project_id, :user_id 
    belongs_to :user 
    belongs_to :project 
end 

我的用戶顯示控制器

def show 
    @user = User.find(params[:id]) 
    @project = Project.find(params[:id]) 
    respond_to do |format| 
    format.html # show.html.erb 
    format.json { render json: @user } 
    end 
end 

我的視圖/用戶/ Show.html.erb表

<table> 
     <tr> 
     <% @projects.each do |p| %> 
      <td><%= p.name %></td> 
     <% end %> 
     </tr> 
    </table> 

回答

0

對於每一個項目,用戶有藍圖,我想說明的項目名稱和鏈接project_path。

對於這些要求,您可以從您的操作中刪除@project分配。你需要看看blueprints關係爲@user,並獲得爲每個blueprints的相關project

<table> 
    <tbody> 
    <% @user.blueprints.each do |blueprint| %> 
     <tr> 
     <td><%= link_to blueprint.project.name, project_path(blueprint.project) %></td> 
     </tr> 
    <% end %> 
    </tbody> 
</table>