Вопрос

I have 2 models: 1) upload 2) date_range

there is an intermediate join table as these models are associated by a many to many relationship thus, each is habtm to the other.

In my view for uploads(index.html.erb) Im trying to show all the date_ranges for a particular upload as follows:

  <tr>

  <th>File name</th>
  <th>Upload Date, Time, Filename</th>
  <th>Type</th>
  <th>Dates in Upload</th>
  <th>Total Rows</th>
  <th>Rows Entered in DB</th>
  <th>Percentage Completed</th>
  <th>Status</th>
  <th>Actions</th>
   </tr>
 </thead>
 <tbody>
     <% @uploads.each do |u| %>
      <tr>

    <td> <%= u.sourcedata_file_name%></td>
         <% path_arr = u.f_path.split("\/")%>
    <td><%= path_arr[-3..-1]%></td>
    <td> <%= u.sourcedata_content_type%></td>
=>>     <td> <%=  u.date_ranges.inspect%>
    <td> <%= u.total_rows%></td>
    <td> <%= u.rows_completed%></td>

like so.

This shows up as follows on the browser:

enter image description here

In my "Dates in Upload" column I want to only show some string with dates like this: "2013-12-25, 2013-12-26" how do I only get these extracted out of the ActiveRecord::Associations::CollectionProxy object as it shows in the image?

Thanks

Это было полезно?

Решение

Use u.date_ranges.pluck(:date_range) to get just the date ranges.

you can then pretty it up with

u.date_ranges.pluck(:date_range).each {|range| puts range}

if you want them in a column.

I see you want them side by side, so it looks like there will only be two because it's a "range" so:

 <%= u.date_ranges.pluck(:date_range).first %>, <%= u.date_ranges.pluck(:date_range).last %>

Другие советы

The simplest thing would probably be to add a to_s method in your DateRange model:

def to_s
  date_range.to_s
end

And in your view, something like:

<%= u.date_ranges.map {|dr| dr.to_s }.join(', ') %>

However, that's really a bit too much code to put right in the view. Better would be to move that to a helper, or even use a presenter pattern. The 'draper' gem can make this kind of thing very easy, so you can do the same transformation in multiple places in your app, and keep your view template much cleaner.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top