I am trying to have an element index view displaying the associated projectname ( field from db project) and the experimenttype ( field from db experiment ) from has_many_through and belongs to/has many associated models
model element.rb
class Element < ActiveRecord::Base
has_many :project_elements
has_many :projects, :through => :project_elements
has_many :experiments
attr_accessible :project_ids, :experiment_ids
model project.rb
class Project < ActiveRecord::Base
has_many :project_elements
has_many :elements, :through => :project_elements
attr_accessible :projectname, :element_ids
model project_element.rb
class ProjectElement < ActiveRecord::Base
belongs_to :project
belongs_to :element
attr_accessible :project_id, :element_id
model experiment.rb
class Experiment < ActiveRecord::Base
belongs_to :element
has_many :welldish_experiments
has_many :welldishs, :through => :welldish_experiments
attr_accessible :exptype, :element_id
elements_controller.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>
when i do this , it shows me the whole associated project objet... same for experiments and i can't figure it out how to restrict the display to one single attribute ?
alternatively since the the datas's been generated using formtastic:
element/_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 %>
i wonder if there is a quick way from there to generate the index view ( with some render 'form' options maybe? ) any help would be appreciated...
the answer was here ( collect method ): http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html
<% @elements.each do |element| %>
<tr>
<td><%= element.projects.collect { |a| a.projectname }%></td>
</tr>
<% end %>