Topic: Foreign key form question

Hello,

I'm new to RoR and I'm working on a forum application. I've a small question about foreign key. Currently users can see forums and click on a forum. Then it displays posts. If user click on a new post it call the method new_topic from my controller :

  def new_topic
    @forum = Forum.find(params[:id])
    @forum.topic.new(params[:topic])
  end

the view looks like this :

<%= error_messages_for(:topic) %>
<%= start_form_tag(:action => "save_topic", :id => @forum) %>
<table>
    <tr>
        <td>Title :</td>
        <td><%= text_field("topic", "titre", "size" => 40 ) %></td>
    </tr>
    <tr>
        <td>Message :</td>
        <td><%= text_area("topic", "message", "cols" => 40, "rows" => 10) %></td>
    </tr>   
    <tr>
        <td></td>
        <td><%= submit_tag("Create") %></td>
    </tr>
</table>
<%= end_form_tag %>

and my save_topic action like this :

  def save_topic
    @forum = Forum.find(params[:id])
    @topic = @forum.topic.new(params[:topic])
    @topic.forum_id = @forum.id
   
    if @topic.save
      flash[:notice] = 'New topic created'
      redirect_to :action => "index_forum", :id => @forum
    else
      render(:action => 'new_topic')
    end
   
  end

My model is ok (forum has_many topics and topics belongs_to forum).

It works nice but I'm not sure it's the best solution to pass foreign key between page/form so I just ask for your opinion in order to continue the development on good basis.

Regards,

Osaris

Re: Foreign key form question

I usually pass it in a hidden field, this way I don't need to set it separately in the controller's create/update action:

# in TopicsController
def new
  @topic = Topic.new(:forum_id => params[:forum_id])
end

def create
  @topic = Topic.new(params[:topic])
  if @topic.save
    #...
  else
    #...
  end
end

# view
<%= start_form_tag :action => "create" %>
<%= hidden_field :topic, :forum_id %>
#...
<%= end_form_tag %>


I changed a few other things too by moving the actions into its own Topics controller. This way the other controller doesn't have multiple scopes.

Railscasts - Free Ruby on Rails Screencasts

Re: Foreign key form question

Thanks for your quick reply. I will try soon. Thanks also for pointing me to the multiple scopes problem. I will separate action related to topics into a Topics controller.