2012-04-18 79 views
1

我有以下型號:如何手動構建表單數據?

Subject has_many Points 
Point belongs_to Subject 

點使用的形式創建的,該控制器如下

def create 
    @subject = Subject.find(params[:subject_id])  
    @point = @subject.points.build(params[:point]) 
    if @point.save 
     flash[:success] = "You have created new data" 
     redirect_to subject_path(@point.subject_id) 
    else 
     render 'new' 
    end 
    end 

目前用戶可以創建使用表單中的每個對象點。不過,我也想讓用戶從csv文件上傳質量點。爲此,我現在用的CSV庫(紅寶石1.9.3)

上傳CSV文件後,我把csv文件到表如下

thegrid = CSV.table(path, :headers => true, :header_converters => :symbol) 

其中path是到CSV。 CSV文件的標題匹配數據庫

我想通過在表中的行循環的列名(包括subject_id列號),並添加每一個到數據庫如下

<% point = Hash.new %> 
    <% thegrid.each do |row| %> 
    <% 
    point = {  
       "name" => row[0], 
       "total_points" => row[1], 
       "subject_id" => row[2] 
      } 
    %> 
    <% @point = @subject.points.build(params[point]) %> 
    <% end %> 

但是上面看起來並沒有將這些行添加到數據庫中。什麼是做這個循環正確的方法,我想這可能是因爲在導致問題

回答

1

我通過更新的代碼如下排序這個問題PARAMS:

<% 
params[:point] = {  
      name: row[0], 
      total_points: row[1], 
      subject_id: row[2] 
     } 
%> 
<% @point = @subject.points.build(params[:point]) %>