collection_select with has_many:通过关系表数据

时间:2011-06-14 10:13:40

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

我有这么可怕的模特:

class ParentalRelation < ActiveRecord::Base
  belongs_to :parent
  belongs_to :student
  belongs_to :counselor
  belongs_to :parental_relation_type
end

class ParentalRelationType < ActiveRecord::Base
  has_many :parental_relations
end

class Parent < ActiveRecord::Base
    has_many :parental_relations
    has_many :students, :through => :parental_relations
    has_many :counselors, :through=> :parental_relations
    has_many :parental_relation_types, :through=> :parental_relations
    belongs_to :user, :dependent=> :destroy
    belongs_to :occupation_type
    accepts_nested_attributes_for :user
end

父母关系类型就像父亲,母亲等。理由是一位辅导员,一位家长和一位学生之间的父母关系是独一无二的,辅导员不应该看到属于其他辅导员的关系。

在controllers / parent_controller / edit操作中,我有:

@parental_relation= ParentalRelation.find_by_counselor_id_and_student_id_and_parent_id(x, y, z)

在views / parent / _form.html.erb中我有:

<%= form_for @parent do |f| %>

在该表单中,我需要ParentalRelationType.all的collection_select,并为该特定的父关系选择父的parental_relation_type_id,但我找不到这样做的语法。

我尝试添加

<%= collection_select(@parental_relation, :parental_relation_type_id, ParentalRelationType.all, :id, :name) %>

在form_for下面,但关系类型id为2,而是选择默认值为1。

1 个答案:

答案 0 :(得分:0)

将此添加到parents / _form

<%= fields_for @counselor_student_parent do |csp| %>
    <%= f.label :parental_relation_type_id %>
    <%= collection_select(:student_counselor_parent, :parental_relation_type_id, ParentalRelationType.all, :id, :name) %>
<% end %>

这是parent_controller / new

def new
    @counselor= Counselor.find(params[:counselor_id])
    @student= Student.find(params[:student_id])
    @parent= @student.parents.build
    @parent_user= @parent.build_user
    @counselor_student_parent= @counselor.student_counselor_parents.build
end
相关问题