Search code examples
rubyruby-on-rails-3formsviewcontrollers

Am I handling this Rails Form Correctly?


In my relationships_controller I have the following:

class RelationshipsController < ApplicationController

  def new
    @user_id = User.find_by_id(params[:user_id])
    @relationship = Relationship.new
  end

  def create
    @relationship = Relationship.new(params[:relationship])
    @relationship.rel_id = User.find_by_id(params[:user_id])
    @relationship.user_id = current_user
    if @relationship.save
        redirect_to root_url, :notice => "Signed Up!"
    else
        render "new"
    end
  end
end

and in my views I have:

<section id="main">
  <%= form_for [@user_id, @relationship]  do |f| %>
    <div class="field">
      <%= f.label :type %>
      <%= select_tag(:type, options_for_select([['Friend', 0], ['Family', 1],['Spouse', 2]])) %>
    </div>
   <div class="actions"><%= f.submit %></div>
  <% end %>
</section>

I have a few questions:

  1. Is this the correct way to handle the rel_id and the user_id? It seems kinda clunky to me.

  2. I can't get the :type to save to the database, but everything else does. I find the following in my server logs:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"z7R4tWSSVHZmFXfh8HocfyuegZ2rwuXXeTLKbR+cLfs=", "type"=>"0", "commit"=>"Create Relationship", "user_id"=>"7"}

which seems odd to me because it should be saving type.

3.. Does it matter if I use @user_id or @current user in the <%= form_for [@user_id, @relationship] do |f| %> line? Why?


Solution

  • 1) @user_id is actually assigned an instance of User, so I would call it @user when assigning rel_id I think you just need the user id value (integer). You can probably just do this:

    @relationship.rel_id = params[:user_id]
    

    2) type fields are used for STI tables with ActiveRecord, and bad things happen if you name your field type for any other reason. Try changing it to another name like relationship_type

    3) Possible, depending on how your app is set up. It's possible that @user(_id) and @current_user represent different users. If you only want the current user to create a relationship for himself/herself, then you can just use @current_user (and maybe not use nested routes in that case).