2013-10-22 113 views
1

我想從我的rails應用程序中的另一個表中引用一列。我想使用兩個表(網站和試用版)中匹配的site_id列來引用site_name。從表中訪問數據

我控制器

def list 
@list = Trial.year(params[:year]).order(:region_id) 
end 

我的模型

class Trial < ActiveRecord::Base 
    attr_accessible :trial_id, :site_id, :year, :trial_type, :region_id 

    scope :year, ->(year) { where(year: year) } 
    scope :trial_id, ->(trial_id) { where(trial_id: trial_id) } 

    belongs_to :site 

end 


class Site < ActiveRecord::Base 
    attr_accessible :site_id, :site_name, :region 

    has_many :trials 

end 

我查看

<table class="table"> 
    <th>Trial Location</th> 
    <th>Trial Type</th> 
    <th>Grower</th> 
    <% @list.each do |list| %> 
    <tr> 
    <td> 
    <%= link_to list.site.site_name, trial_trials_path(trial_id: list.trial_id) %> 
    </td> 
    <td>  
    <%= link_to list.trial_type, trial_trials_path(trial_id: list.trial_id) unless list.trial_type.blank? %> 
    </td> 
    <td>  
    <%= link_to list.trial_type, trial_trials_path(trial_id: list.trial_id) unless list.trial_type.blank? %> 
    </td> 
    </tr> 
    <% end %> 
</table> 
+0

爲什麼網站表和試驗表都有'site_id'?我期望'試驗'有'site_id'和'網站'有一個主鍵'ID'列 –

+0

謝謝瑞安,你帶領我在正確的方向。我使用了一個客戶主鍵:belongs_to:site,:primary_key =>'site_id',它起作用。 – Grinskull

回答

0

建立模型中的關聯不寫getter方法適合你。 attr_accessibles設置了該方法。

添加:網站到您的審判attr_accessible