2

Rails Guides の例で遊んでいます:

http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association

この例では、モデルに対して次の設定が行われています。

class Physician < ActiveRecord::Base
  has_many :appointments
  has_many :patients, :through => :appointments
end

class Appointment < ActiveRecord::Base
  belongs_to :physician
  belongs_to :patient
end

class Patient < ActiveRecord::Base
  has_many :appointments
  has_many :physicians, :through => :appointments
end

次の2つのことを行う方法を理解しようとしています。

  1. 新しい患者を作成し、予約時間のある既存の医師に予約を割り当てるビューをセットアップするにはどうすればよいですか
  2. 既存の患者に、新しい医師と予約時間の予約を割り当てるにはどうすればよいですか

入れ子になったフォームを処理する RailsCasts 196 と 197 を調べましたが、この状況にどのように適用されるかわかりません。

誰かが例を提供するか、これに関するガイドを教えてもらえますか?

ありがとうございました

4

1 に答える 1

3

まず、医師 ID をPatientsController#newアクションに渡す必要があります。ユーザーがリンクをたどってそこにたどり着いた場合、これは次のようになります

<%= link_to 'Create an appointment', new_patient_path(:physician_id => @physician.id) %>

または、ユーザーがフォームを送信する必要がある場合は、隠しフィールドを一緒に送信できます。

<%= f.hidden_field :physician_id, @physician.id %>

次に、でPatientsController#new

def new
  @patient = Patient.new
  @physician = Physician.find(params[:physician_id])
  @patient.appointments.build(:physician_id => @physician.id)
end

new.html.erb

<%= form_for @patient do |f| %>
  ...
  <%= f.fields_for :appointments do |ff |%>
    <%= ff.hidden_field :physician_id %>
    ...
  <% end %>
<% end %>
于 2012-07-14T05:48:00.723 に答える