添加关联到HaBtM关系的连接表

时间:2016-03-08 23:05:48

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

我目前有3个模型(用户,配对,会议)和联接表meeting_pairings。

User.rb

class User < ActiveRecord::Base

  enum role: [:student, :supervisor, :admin]

  has_many :students, class_name: "User",
                      foreign_key: "supervisor_id"

  belongs_to :supervisor, class_name: "User"

  has_and_belongs_to_many :pairings

end

Pairings.rb

class Pairing < ActiveRecord::Base

  has_and_belongs_to_many :supervisor, class_name: 'User'
  belongs_to :student, class_name: 'User'

  has_and_belongs_to_many :meetings, join_table: :meetings_pairings

end

Meetings.rb

class Meeting < ActiveRecord::Base

    enum status: [:available, :unavailable]

    has_and_belongs_to_many :pairings, join_table: :meetings_pairings

end

Schema.rb(相关位)

  create_table "meetings", force: :cascade do |t|
    t.date     "meeting_date"
    t.datetime "meeting_time"
    t.integer  "status",       default: 0, null: false
    t.boolean  "accepted"
  end

  create_table "meetings_pairings", id: false, force: :cascade do |t|
    t.integer "pairing_id"
    t.integer "meeting_id"
  end

  add_index "meetings_pairings", ["meeting_id"], name: "index_meetings_pairings_on_meeting_id"
  add_index "meetings_pairings", ["pairing_id"], name: "index_meetings_pairings_on_pairing_id"

  create_table "pairings", force: :cascade do |t|
    t.integer  "supervisor_id"
    t.integer  "student_id"
    t.string   "project_title"
  end

  add_index "pairings", ["student_id"], name: "index_pairings_on_student_id", unique: true
  add_index "pairings", ["supervisor_id"], name: "index_pairings_on_supervisor_id"

我创建了视图和控制器,以使用户(管理员,正在配对)创建会议。但是,我不知道如何将此关联添加到连接表。

meetings_controller.rb

class MeetingsController < ApplicationController

    def index
        @meetings = Meeting.all
    end

    def new
        @meeting = Meeting.new
    end

    def create
        @meeting = Meeting.new(meeting_params)
        if @meeting.save
      redirect_to meetings_path, :notice => "Meeting Created!"
    else 
      redirect_to meetings_path, :notice => "Meeting Failed!"
    end
  end

  def show
    @meeting = Meeting.find(params[:id])
  end  

  private
  def meeting_params
    params.require(:meeting).permit(:meeting_date, :meeting_time)
  end

end

视图中的表格

<%= form_for @meeting do |f| %>
  <div class="field">
    <%= f.label :meeting_date %><br />
    <%= f.text_field :meeting_date %>
  </div>
  <div class="field">
    <%= f.label :meeting_time %><br />
    <%= f.time_select :meeting_time, :ampm => true, :minute_step => 30, :default => {:hour => '9', :minute => '0'} %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

这会在会议表中创建一个条目,所以我的问题是如何才能创建一个条目,以便使用创建会议的当前用户的配对ID进入连接表?

1 个答案:

答案 0 :(得分:0)

决定使用has_many:through(用户会议用户)关系。问题不再适用。