views:

24

answers:

2

I have a User and Group model. User has_many Groups and Group belongs_to User

I already have entries in the user table:

id    name
--------------
1     testuser
2     someotheruser

Imagine if the user with id 1 (testuser) is logged in and I want to create groups inside that user.

When I create a new group from new action in Group Controller the entries in the DB are going like this:

   id   groupname   user_id
   ------------------------
   1    groupA
   2    groupB

as you see, user_id, column is always going in as blank so the association is not there.

What do I need to do to make this association?

code for GroupsController:

  def new
    @group = Group.new
  end

  def create
    @group = Group.new(params[:group])
    if @group.save
      flash[:notice] = "Successfully created group."
      redirect_to groups_url
    else
      render :action => 'new'
    end
  end

code for views/groups/new.html.erb

<% title "New Group" %>

<% form_for @group do |f| %>
  <%= f.error_messages %>
  <p>
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </p>
  <p>
    <%= f.label :description %><br />
    <%= f.text_field :description %>
  </p>
  <p><%= f.submit %></p>
<% end %>


<p><%= link_to "Back to List", groups_path %></p>

I am new to rails please tell me how to make association with the user. From the console I am able to make the association by adding groups for a user like this:

@u = User.find(1)
@u.groups.create(:groupname=>"groupA")
@u.save

but I dont know how to get this done from the front end.

A: 

You need to make sure your user id is part of the params passed to Group.new, perhaps something like this:

def create
  @group = Group.new(params[:group].merge!({:user_id => current_user}))
  if @group.save
    flash[:notice] = "Successfully created group."
    redirect_to groups_url
  else
    render :action => 'new'
  end
end

You may want to add a flash[:error] in your else clause as well otherwise it would be confusing to the user to end up on the new action with no explanation.

Warren
A: 

First you'll want to make sure that a group can't be saved without a user:

/app/models/group.rb

class Group
  belongs_to :user
  validates_presence_of :user
end

Then, lets default the group to be the current user.

/app/controllers/groups_controller.rb

def create
  @group = Group.new(params[:group])
  @group.user = current.user
  if @group.save
    ...
  else
    ...
  end
end

You could also do a @group.user = current_user if @group.user.nil? but it sounds like the only person to create a group will be the current user.

Jesse Wolgamott
thanks I'll try this. I was going to try the approach of passing the hidden field with user_id but this is much better
Patrick