bjoern
bjoern

Reputation: 1019

Creating form to update relationship table and model table

I have 3 models:

Every event has multiple vendors through that relationship.

Now I want to create a form at /events/1/add_vendors which creates the relationship AND creates the vendor model.

How would I go about doing this?

Thanks for the help!

Upvotes: 0

Views: 114

Answers (2)

plasticide
plasticide

Reputation: 1240

ensure that you're Event model looks something like this:

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

accepts_nested_attributes_for :vendor_relationships

your VendorRelationship model looks something like this:

attr_accessible :vendors, :vendors_attributes
has_many :vendors

accepts_nested_attributes_for :vendors

in your EventController:

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

and in your create view, something like:

<% 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 %>

That's one way. Another, probably better user experience would be to allow for selection of vendor from existing vendors or create new. Create new would ajax creation to the VendorController, and on creation, return the vendor's information to the form. Saving the relationship would ajax a call to create the vendor_relationship and display the result.

Hope that sends you down the right direction.

Upvotes: 1

Valery Kvon
Valery Kvon

Reputation: 4496

# 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 %>

Upvotes: 0

Related Questions