user1224344
user1224344

Reputation: 129

Form not submitting to custom action

I'm still relatively new to Rails and have looked through many similar questions here, but none helped me thus far. So... I have a form that I'd like to send a simple email. It pops up in a Bootstrap modal and looks like:

.form-horizontal
  = form_tag :url => { :action => :share_event }, remote: true, html: {"data-type" => :json} do
    .control-group
      = label_tag :to
      = text_field_tag :to
    .control-group
      = label_tag :from
      = text_field_tag :from
    .control-group
      = label_tag :subject
      = text_field_tag :subject  
    - hidden_field_tag :event_url, :value => url
    .actions
      = submit_tag 'share event', :class => "btn btn-mini submit"

and in my controller:

def share_event
  @to = params[:to]
  @from = params[:from]
  @subject = params[:subject]
  @url = params[:url]
  respond_to do |format|
    EventMailer.share_event(@to, @from, @subject, @url).deliver
    redirect_to events_path, notice: 'Event sent'
  end 
end

  EventMailer.share_event(@to, @from, @subject, @url).deliver
end

routes:

resources :events do
  post :share_event, :on => :collection
end

The problem is when I submit it uses the 'create' action as opposed to 'share_event'. I've tried many approaches, but it keeps on using 'create'. Here are an extract from the logs:

Started POST "/events?html%5Bdata-type%5D=json&remote=true&url=share_events_path" for 41.134.48.225 at 2012-11-06 15:34:25 +0100
Processing by EventsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"7/6pg9XX/N09qUB+SUlWOdpCsgPOAiXM+nC+mq6VtKE=", "to"=>"[email protected]", "from"=>"[email protected]", "subject"=>"gfh", "event_url"=>"{:value=>\"http://events.example.com/events/3\"}", "commit"=>"share event »", "html"=>{"data-type"=>"json"}, "remote"=>"true", "url"=>"share_events_path"}

Any help/advice would be appreciated.

Many thanks!

Upvotes: 0

Views: 580

Answers (1)

HungryCoder
HungryCoder

Reputation: 7616

I can't surely tell what was the issue, but guess it's in your form_tag declaration. You can try this following modifications

in your route.rb

resources :events do
  collection { post :share_event }
end

in your view

Replace:

= form_tag :url => { :action => :share_event }, remote: true, html: {"data-type" => :json} do

with:

= form_tag(share_event_events_path({format: 'json'}), remote: true) do

Please check the form_tag api doc.

if that works, suggested naming are:

routes.rb

resources :events do
  collection { post :share }
end

So, you can call it share_events_path as

= form_tag(share_events_path({format: 'json'}), remote: true) do

Upvotes: 1

Related Questions