I have the models User and Group, and the join table Membership which uses has_many :through method. In my join table’s form, I want the user to input a valid group name that an administrator has created to become a member of that group.
I have gotten the case where a valid name is entered to work but now I need some validation if they input a blank text box, or that the inputted group name exists in the database, I’d like some nice error messages. I thought this would be possible through some validates method?
membership partial _form.html.erb
<%= form_for(@membership) do |f| %>
<% if @membership.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@membership.errors.count, "error") %> prohibited this membership from being saved:</h2>
<ul>
<% @membership.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :group %><br />
<%= f.text_field :group %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
membership.rb
class Membership < ActiveRecord::Base
belongs_to :group
belongs_to :user
attr_accessible :user_id, :group_id
validates_uniqueness_of :group_id, :message => "can be only joined once", :scope => 'user_id'
validates_presence_of :group, :user
end
group.rb
class Group < ActiveRecord::Base
has_many :memberships, :dependent => :destroy
has_many :users, :through => :subscriptions
validates :name, :presence => true, :uniqueness => true
attr_accessible :name, :expiry
end
So need some direction as how the validation happens because the above validation in the membership and group models doesn’t work, I get the error for both empty text box or name not in the database…
Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
Edit: Added controller code below
def create
@group = Group.find_by_name(params[:membership][:group])
@membership = current_user.memberships.build(:group_id => @group.id)
respond_to do |format|
if @membership.save
format.html { redirect_to membership_url, :notice => 'Membership was successfully created.' }
format.json { render :json => @membership, :status => :created, :location => @membership }
else
format.html { render :action => "new" }
format.json { render :json=> @membership.errors, :status => :unprocessable_entity }
end
end
end
I solved this question by changing the text input box to a select field, and will add a password field to the model to solve my issue of unwanted users joining the group.
After which my model validation works now below