Reputation: 303
I have a User and Group model that I bind with an Assignments model. A user has_many groups and a group has_many users. However, when I create a new group, when I do Group.last.users.count
the output is 0 or ActiveRecord::Associations::CollectionProxy []. Do I need to change an aspect of my simple_form? Did I not build the middleman model correctly to bind users and groups? I would like it so that when a user creates a group, the group_ids are in the array when doing User.last.groups
, etc. When I had it as User has_many groups and a Group belongs_to user, the group ids would be tied to a user. But since switching to has_many for both models and introducing the Assignments model, this is no longer the case.
Group Model
class Group < ActiveRecord::Base
validates :user_id, presence: true
has_many :assignments
has_many :users, through: :assignments
has_many :posts
has_many :attachments
has_secure_token
end
User Model
class User < ActiveRecord::Base
...
has_many :assignments
has_many :groups, through: :assignments
accepts_nested_attributes_for :assignments
...
Assignment Model
class Assignment < ActiveRecord::Base
belongs_to :group
belongs_to :user
accepts_nested_attributes_for :group
accepts_nested_attributes_for :user
end
Groups Controller
class GroupsController < ApplicationController
before_action :authenticate_user!
def new
@group = current_user.groups.build
end
def create
@group = current_user.groups.build(group_params)
@group.user_id = current_user.id
if @group.save
redirect_to groups_path
else
render :new
end
end
private
def group_params
params.require(:group).permit(:group_name, :description, :user_id)
end
end
Group new.html.erb
<%= simple_form_for @group do |f| %>
<%= f.input :group_name %>
<%= f.text_area :description %>
<%= f.button :submit %>
<% end %>
Upvotes: 1
Views: 1373
Reputation: 5895
You can do something like that:
I guess the build
method seems not saving the joiner model you can use new
. There is an issue here:
As there is many-to-many relation between Group
and User
. Thus there is no need for user_id
in group. Thus the validation is unnecessary. And it causes the problem with my first approach. In model comment the validation. # validates :user_id, presence: true
def create
@group = current_user.groups.new(group_params)
# @group.user_id = current_user.id // this line is unnecessary
if @group.save
redirect_to groups_path
else
render :new
end
end
Or, (I'll not suggest it as it is not a good approach)
def create
@group = Group.new(group_params)
if @group.save
current_user.groups << @group
redirect_to groups_path
else
render :new
end
end
Upvotes: 2