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.