2011-04-28 69 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} %>