ReportsController中的ActiveRecord :: UnknownAttributeError #import unknown attribute' relation'为学生

时间:2017-03-25 12:47:50

标签: ruby-on-rails ruby

我通过Excel将一些数据导入我的Rails应用程序。导入工作正常,但是当我尝试导入监护文件时,我收到错误:

  

未知属性'关系'为学生。

此字段不属于学生,但在导入期间,当我选择学生导入文件时,它会以适当的方式插入。 但是当我导入Guardian文件时,它会向我显示错误。

我尝试调试代码params[:role] == :guardian ? Guardian : Student

我得到了这个

`[1] pry(#<ReportsController>)> params[:role] == :guardian ? Guardian : Student
=> Student(id: integer, admission_no: string, class_roll_no: string, admission_date: date, first_name: string, middle_name: string, last_name: string, batch_id: integer, date_of_birth: date, gender: string, blood_group: string, birth_place: string, nationality_id: integer, language: string, religion: string, category_id: integer, address_line1: string, address_line2: string, city: string, state: string, pin_code: string, country_id: integer, phone1: string, phone2: string, email: string, immediate_contact: integer, is_sms_enabled: boolean, status_description: string, is_active: boolean, is_deleted: boolean, created_at: datetime, updated_at: datetime, image_file_name: string, image_content_type: string, image_file_size: integer, image_updated_at: datetime)`

它只会转到else部分,只接受学生档案。

控制器

def importer      
  params[:role] == :guardian ? Guardian : Student
end

def import
  importer.import(params[:file])
  redirect_to import_reports_path, notice: "Students imported."
end

student.rb

COLUMNS_TO_STRING = ["batch_id", "class_roll_no","phone1","phone2"]  # and so on
def self.import(file)
  spreadsheet = open_spreadsheet(file)
  header = spreadsheet.row(1)
  (2..spreadsheet.last_row).each do |i|
  row = Hash[[header, spreadsheet.row(i)].transpose]
  row = clean_for row, COLUMNS_TO_STRING
  record = Student.find_by(:id => row["id"],:batch_id =>    row["batch_id"],:class_roll_no => row["class_roll_no"],:phone1 =>  row["phone1"],:phone2 => row["phone2"]) || new
  record.attributes = row.to_hash.slice(*row.to_hash.keys)
  record.save!  
 end
end

guardian.rb

COLUMNS_TO_STRING = ["student_id"] # and so on
def self.import(file)
  spreadsheet = open_spreadsheet(file)
  header = spreadsheet.row(1)
  (2..spreadsheet.last_row).each do |i|
  row = Hash[[header, spreadsheet.row(i)].transpose]
  row = clean_for row, COLUMNS_TO_STRING
  guardian = Guardian.find_by(:id => row["id"],:student_id => row["student_id"]) || new
  guardian.attributes = row.to_hash.slice(*row.to_hash.keys)
  guardian.save!
 end
end

查看

<h1>IMPORT</h1>
<div class = "well">
    <p>
        <%= form_tag import_reports_path do %>
        <%= file_field_tag :file%>
        <br>
        <%= submit_tag "Import",class: "btn btn-primary" %>
        <% end %>
    </p> 
</div>

1 个答案:

答案 0 :(得分:0)

你确定不是一个字符串吗?尝试

def importer      
  params[:role] == 'guardian' ? Guardian : Student
end