1

我试图让一个元素索引视图显示关联的项目名称(来自 db 项目的字段)和来自 has_many_through 的实验类型(来自 db 实验的字段),并且属于/具有许多关联模型

模型元素.rb

class Element < ActiveRecord::Base

has_many :project_elements   
has_many :projects, :through => :project_elements

has_many :experiments

attr_accessible :project_ids, :experiment_ids

模型项目.rb

class Project < ActiveRecord::Base

has_many :project_elements
has_many :elements, :through => :project_elements  

attr_accessible :projectname, :element_ids

模型 project_element.rb

class ProjectElement < ActiveRecord::Base
belongs_to :project
belongs_to :element
attr_accessible :project_id, :element_id

模型实验.rb

class Experiment < ActiveRecord::Base

belongs_to :element

has_many :welldish_experiments
has_many :welldishs, :through => :welldish_experiments

attr_accessible :exptype, :element_id

元素控制器.rb

  def index
   @elements = Element.all
   respond_to do |format|
     format.html # index.html.erb
     format.json { render json: @elements }
     end

/elements/index.html.erb

 <% @elements.each do |element| %>
  <tr>

    <td><%= element.experiments %></td>
    <td><%= element.projects %></td>    

当我这样做时,它向我展示了整个相关的项目对象......对于实验来说也是如此,我无法弄清楚如何将显示限制为一个属性?

或者,因为数据是使用formtastic生成的:

元素/_form.html.erb

       <%= semantic_form_for @element do |f| %>    
       <%= f.inputs do %>  
         <%= f.input :projects, :label => "projet associé", :required => true%>
         <%= f.input :experiments, :label => "type d'experience",
     :as => :radio,       :collection => Experiment.all, :required => true %>    
       <% end %>
       <%= f.actions :submit, :cancel %>
       <% end %>

我想知道是否有一种快速的方法可以从那里生成索引视图(可能带有一些渲染“表单”选项?)任何帮助将不胜感激......

4

1 回答 1

1

答案在这里(收集方法): http ://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

  <% @elements.each do |element| %>
       <tr>          
       <td><%= element.projects.collect { |a| a.projectname }%></td>
       </tr>
  <% end %>
于 2012-06-18T15:53:27.520 回答