如何将多关系表导出到csv?

时间:2016-05-07 18:08:26

标签: ruby-on-rails ruby

如何将表格导出到csv?我知道如何从单个模型表导出数据,但在我的表中,有三个不同模型的属性。我找到了this,但我不知道如何根据自己的需要修改此代码。

我也知道我应该将类方法更改为范围,但是在解决导出表到csv的问题之后我会这样做。

表:

%table.table
  %tr
    %th= @match.date.strftime("%e/%m/%Y")

  %tr
    %th= @match.address

  %tr
    %th Time
    %th Home
    %th Away
    %th Referee
    %th Time/scorekeeper
    %th Assessor

  %tr
    %td= @match.date.strftime("%H:%M")
    %td= @match.club_home
    %td= @match.club_away
    %td
      - @referees.each do |referee|
        %p #{referee.showcase.name} [#{referee.showcase.level}]
    %td
      - @scorekeeper.each do |scorekeeper|
        = scorekeeper.showcase.name
        %br/

    %td
      - @assessor.each do |assessor|
        = assessor.showcase.name

匹配模型:

class Match < ActiveRecord::Base

  validates :club_home, presence: true, length: { in: 3..60 }
  validates :club_away, presence: true, length: { in: 3..60 }
  validates :date,      presence: true
  validates :address,   presence: true

  has_and_belongs_to_many :showcases
  has_many :roles
  accepts_nested_attributes_for :roles, :reject_if => :all_blank

  def referees
    self.roles.where(role_type: "Referee")
  end

  def scorekeeper
    self.roles.where(role_type: "Time/Scorekeeper")
  end

  def assessor
    self.roles.where(role_type: "Assessor")
  end
end

匹配控制器:

class MatchesController < ApplicationController

  before_action :authenticate_user!, only: [:new, :create, :edit, :update, :destroy]
  before_action :authenticate_admin, only: [:new, :create, :edit, :update, :destroy]

  def index
    @matches = Match.all
    @matches_grid = initialize_grid(Match)


    respond_to do |format|
      format.html
      format.csv { send_data @matches }
    end
  end

  def show
    @match = Match.find(params[:id])
    @referees = @match.referees
    @scorekeeper = @match.scorekeeper
    @assessor = @match.assessor

  end

  def new
    @match = Match.new
    @match.roles.build
  end

  def create
    @match = Match.new(match_params)
    if @match.save
      flash[:success] = "Match created"
      redirect_to matches_path
    else
      render 'new'
    end
  end

  def edit
    @match = Match.find(params[:id])
    @match.roles.build
  end

  def update
    @match = Match.find(params[:id])
    if @match.update_attributes(match_params)
      flash[:success] = "Match updated"
      redirect_to @match
    else
      render 'edit'
    end
  end

  def destroy
    @match = Match.find(params[:id])
    @match.destroy
    flash[:success] = "Match destroyed"
    redirect_to matches_path
  end

  private

  def match_params
    params.require(:match).permit(:club_home, :club_away, :date, :address, roles_attributes: [ :id, :showcase_id, :role_type ])
  end

end

0 个答案:

没有答案