I have a problem when trying to create a membership for users based on the name they input into the membership form – new.html.erb.
user.rb
has_many :memberships, :dependent => :destroy
has_many :groups, :through => :memberships
membership.rb
class Membership < ActiveRecord::Base
attr_accessible :user_id, :group_id
belongs_to :user
belongs_to :group
end
group.rb
has_many :memberships, :dependent => :destroy
has_many :users, :through => :memberships
membership controller
def create
@group = Group.find_by_name(:group)
@membership = current_user.memberships.build(:group_id => @group.group_id)
if @membership.save
flash[:notice] = "You have joined this group."
redirect_to :back
else
flash[:error] = "Unable to join."
redirect_to :back
end
end
membership – _form.html.erb
<%= form_for(@membership) do |f| %>
...
#error validation
...
<div class="field">
<%= f.label :group %><br />
<%= f.text_field :group %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
What I want it to do is find the group inputted if it exists, and create the table entry in the memberships table accordingly. Just not sure if what I’m doing is on the right track. Any suggestions?
The reason your code isn’t working now is because of this line:
it should be something like (I don’t remember exactly sorry)
The error is getting called on the next line because
@groupisnil.But you should probably handle that type of logic in the model anyway with a virtual attribute or something.
membership.rb
form
controller