views:

21

answers:

1

I have a partial that contains a form:

<% form_for :message, :url => { :action => "create" }, :html => { :id => 'form' } do |f| %>
  <%= f.error_messages %>

  <%= f.label :title, "title" %>
  <%= f.text_field :title %>

  <%= f.label :tag, "tag" %>
  <% if controller.controller_name == "tags" %>
    <%= f.text_field :tag_list, :value => @title %>
  <% else %>
    <%= f.text_field :tag_list %>
  <% end %>

  <%= f.label :name, "name" %>
  <%= f.text_field :name %>

  <%= f.label :email, "email" %>
  <%= f.text_field :email %>

  <%= f.label :title, "message" %>
  <%= f.text_area :content %>

  <%= f.submit 'submit' %>

<% end %>

I'm using this in two controllers: messages and tags. It works fine in the messages controller but not in the tags controller. When it's rendered in tags#show it autofills the tag field. When a message is submitted from tags#show I'm redirected to the root of the website with a flash error "Tag does not exist."

tags controller:

class TagsController < ApplicationController
  before_filter :redirect_if_doesnt_exist#, :only => :show

  def show
    @title = Tag.find(params[:id]).name
    @tag = Tag.find(params[:id])
    @entries = Entry.paginate(Entry.find_tagged_with(@tag), 
            :page => params[:page], :per_page => 10, :order => "name")
    @messages = Message.paginate(Message.find_tagged_with(@tag), 
            :page => params[:page], :per_page => 10, :order => "updated_at DESC")
    @related_entries = Entry.tagged_with(@tag, :on => :tags)
    @related_tags = @related_entries.collect{|x|x.tags}.flatten.uniq
    @related_tags.delete(@tag)
  end

  private
  # Redirect if requested tag does not exist
  def redirect_if_doesnt_exist
    @tag = Tag.find(params[:id]) rescue nil
    if @tag.nil? # maybe "or @tag.empty?" could solve the empty tag issue
      flash[:error] = 'Tag does not exist.'
      redirect_to '/'
    end
  end
end

In case it isn't clear: The partial is shown in the view, the form within it just doesn't submit the data from the tags controller and is redirected. The partial works fine from the messages controller. This is a Rails 2.3.x application. Thank you for reading my question, your time is appreciated.

+1  A: 

Your problem is the URL of the form partial is only the action:

<% form_for :message, :url => { :action => "create" }, :html => { :id => 'form' } do |f| %>

If you include this in a view that isn't under messages_controller, it'll call the wrong action. If you include this ina a tags view, it'll try to call the create action for tags_controller instead.

It'll probably work if you just add the controller too:

<% form_for :message, :url => { :controller => :messages, :action => :create }, :html => { :id => 'form' } do |f| %>
Karl
Thank you so much!