我们可以手动将一个条目添加到动态下拉列表中,如果那么在Ruby On Rails中如何

时间:2013-07-31 10:52:55

标签: ruby-on-rails-3.1

我有一个student,student_parent和address_detail表我想在address_detail表中添加学生及其父(父亲和母亲)地址,我有表之间的关系

学生: - has_many:student_parents has_many:address_details

Student_parent: belongs_to:学生 has_many:address_detail

address_detail: belongs_to:学生 belongs_to:student_parent

在address_detail表单中我只有父亲和母亲的下拉列表我想手动添加学生条目我该怎么办,这是我的地址_详细信息``

    <%= simple_form_for @address_detail, :html => { :class => 'form-horizontal' } do |f| %>
<div class="control-group">
  <label  class = "control-label"> Address Correspond To <abbr title="required">*</abbr></label>
  <div class="controls">
    <%= f.collection_select(:student_parent_id, student_parent_relation_collection , :id, :relation_to_student, {:prompt => true}, :required =>true  )%>
    <%= f.hidden_field :student_id, :value => current_student_id %>
  </div>
</div>

.... .....

这是Address_correspond_to下拉方法的Helper方法

# return collection of parent relation to student

def student_parent_relation_collection

if current_user != nil
  student =  Student.find_all_by_user_id(current_user.id)
  logger.info "student_is = #{student}"
  if student != nil
  return  StudentParent.find_all_by_student_id(student)
 end
end

目前的OutPut是 父亲 母亲

我想出去 学生 父亲 母亲

2 个答案:

答案 0 :(得分:0)

if current_user
  student =  Student.find_by_user_id(current_user.id)
  return [student] + student.student_parents if student
end

答案 1 :(得分:0)

Class AddressDetail < ActiveRecord::Base

  def student_and_parents
    [student, student_parent]
  end

end

然后,在视图中,您可以参考

address_detail.student_and_parents

或在用户

Class User < ActiveRecord::Base

  has_many :students
  has_many :student_parents, :through => :students

  def students_and_parents
    [students, student_parents].compact.flatten
  end

end

你可以参考

current_user.try(:students_and_parents)