0

I have 3 models:

  • event
  • vendor
  • vendor_relationship

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!

bjoern
  • 1,009
  • 3
  • 15
  • 31

2 Answers2

1

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.

plasticide
  • 1,242
  • 9
  • 13
  • What happens when you run something like @vendor.vendorships.build()? Does that create the vendorship object? I guess i'm missing some rails theory. Thanks though, your answer pointed me into the right direction. I ended up just creating a form for Vendor passing in the event_id as a hidden field and then creating the relationship model (vendorhsip) in the vendor controller. – bjoern Jan 09 '13 at 14:53
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 %>
Valery Kvon
  • 4,438
  • 1
  • 20
  • 15