从名称访问id

时间:2012-08-16 12:57:57

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1 ruby-on-rails-3.2

class SubjectTeachersController < ApplicationController

def new
  @st = SubjectTeacher.new   
  @tnames = Teacher.pluck(:tname)
  @subs = Subject.pluck(:sub_name)

end    

def create
   @tech = Teacher.find(params[:tname]).id
   @sub = Subject.find(params[:sub_name]).id
   @st = SubjectTeacher.create(:teacher_id => @tech, :subject_id => @sub )
    if @st.save
        flash[:notice] = " creates successfully"
    else
      render('new')
        end    
  end   
end 

我创造了mamy与Subject&amp ;;之间的许多关系。老师。 SubjectTeacher是Subject&amp; amp;老师。在SubjectTeacherController中。

这里,@ tnames存储所有教师姓名,而@subs存储所有科目名称。我想在控制器中访问两者的ID ...怎么样?  我是否应该在创建功能中进行任何更改?请打电话给我......

1 个答案:

答案 0 :(得分:1)

Rails提供{魔术'查找器方法,格式为Model.find_by_attribute

在这种情况下,我们可以使用Teacher.find_by_tname(params[:tname])Subject.find_by_sub_name(params[:subname])