0

私は3つのモデルを持っています:

  • イベント
  • ベンダー
  • vendor_relationship

すべてのイベントには、その関係を通じて複数のベンダーがあります。

ここで、/ events / 1 / add_vendorsにフォームを作成して、関係を作成し、ベンダーモデルを作成します。

どうすればこれを行うことができますか?

助けてくれてありがとう!

4

2 に答える 2

1

Eventモデルが次のようになっていることを確認します。

attr_accessible :vendor_relationships, :vendor_relationships_attributes
has_many :vendor_relationships
has_many :vendors, :through => :vendor_relationships

accepts_nested_attributes_for :vendor_relationships

VendorRelationshipモデルは次のようになります。

attr_accessible :vendors, :vendors_attributes
has_many :vendors

accepts_nested_attributes_for :vendors

あなたのEventController

@event = Event.new(params[:event])

作成ビューでは、次のようになります。

<% form_for Event.new do |f| %>
  <%= f.text_field, :field_for_the_event %>
  <% f.fields_for :vendor_relationships do |rf| %>
    <%= rf.text_field, :price_maybe? %>
    <% rf.fields_for :vendor do |vf| %>
      <%= vf.text_field, :name_and_so_on %>
    <% end %>
  <% end %>
<% end %>

それは一つの方法です。別のおそらくより良いユーザー エクスペリエンスは、既存のベンダーからベンダーを選択できるようにするか、新しいベンダーを作成できるようにすることです。Create new は VendorController への ajax 作成を行い、作成時にベンダーの情報をフォームに返します。リレーションシップを保存すると、呼び出しが ajax されて vendor_relationship が作成され、結果が表示されます。

それがあなたを正しい方向に導くことを願っています。

于 2013-01-07T05:17:32.070 に答える
0
# routes.rb

resources :events do
  resources :vendors, :path_names => { :new => 'add_vendors' }
end

# vendors_controller.rb

before_filter :load_event
before_filter :load_vendor, :only => [:edit, :update, :destroy]

def load_vendor
  @vendor = (@event ? @event.vendors : Vendor).find(params[:id])
end

def load_event
  @event = params[:event_id].present? ? Event.find(params[:event_id]) : nil
end

def new
  @vendor = @event ? @event.vendors.build : Vendor.new
  ...
end

def create
  @vendor = @event ? @event.vendors.build(params[:vendor]) : Vendor.new(params[:vendor])
  ...
end

def edit
  ...
end

def update
  ...
end

def destroy
  ...
end

# View form

<%= form_for([@event, @vendor]) do |f| %>
  ...
<% end %>
于 2013-01-07T05:25:49.533 に答える