2011-04-28 116 views
4

我需要幫助分配學生批次..他們是在多對多的關係。幫助與rails link_to和發佈方法

 <tbody> 
      <% Batch.all.each do |b|%> 
      <tr> 
       <td><%= b.course.name%></td> 
       <td><%= b.name %></td> 
       <td><%= b.section_name%></td> 
       <td><%= link_to "Add", student_batch_students_path(@student, :batch_id=> b.id), :method=> :post%></td> 
      </tr> 
      <%end%> 


     </tbody> 

在我的控制器

def create 
    @batch_student = BatchStudent.new(params[:batch_student]) 
    @batch_student.save  
    end 

我的路線

resources :students do 
    resources :batch_students 
    end 

resources :batches 

但在我的數據庫將其與student_id數據和BATCH_ID爲空

+0

你得到什麼錯誤? – fl00r 2011-04-28 17:11:50

+0

我在原文中增加了更多細節 – ignaciofuentes 2011-04-28 17:12:47

+0

顯示你的'student_batch'動作和你的路線 – fl00r 2011-04-28 17:13:02

回答

20

要更新存在一批創建它,但不創建,所以你應該提出PUT請求到update ac和

<td><%= link_to "Add", student_batch_students_path(@student, :batch_id => b.id), :method=> :post %></td> 


def create 
    @student = Student.find(params[:id]) 
    @batch = Batch.find(params[:batch_id]) 
    @batch_student = BatchStudent.new(:params[:batch_student]) 
    @batch_student.student = @student 
    @batch_student.batch = @batch 
    @batch_student.save 
end 
+0

根本不是這種情況...我想創建一個BatchStudent ...(實質上是爲相關學生分配一個新批次) – ignaciofuentes 2011-04-28 17:20:33

+0

在你的鏈接中有'student_batch_students_path(@student,:batch_id => b .id)'這意味着你有'b'對象。或者你完全錯過了 – fl00r 2011-04-28 17:21:40

+0

當然,我有b對象...你可以看到這是在一個表中首先顯示所有的批次,它也顯示link_to批次給學生 – ignaciofuentes 2011-04-28 17:26:56

2

該參數散列不包含:batch_student散列,因爲您不是從窗體提交。參數應該看起來像{"student_id" => 1, "batch_id" => 1, "method" => "post"}

所以,修改你的創建操作如下:

def create 
    @batch_student = BatchStudent.new(params) 
    @batch_student.save  
end 

# or, a shorter version 
def create 
    @batch_student = BatchStudent.create(params) 
end 

採用新型的優點是你可以做一個if @batch_student.save檢查錯誤。

我希望這會有所幫助。

+0

它是有道理的..問題是,它也是發送方法和真實性標記...所以我得到一個未知的屬性「方法:錯誤 – ignaciofuentes 2011-04-28 19:38:18

+0

@ignaciofuentes使用'params.permit(:student_id,:batch_id)'以避免這種情況。 – AmShaegar 2014-10-14 12:14:35

0

的參數和HTTP方法應該在一起{:batch_id=> b.id, :method=> :post}

<%= link_to "Add", student_batch_students_path(@student), {:batch_id=> b.id, :method=> :post} %>