0

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?

Norto23
  • 2,249
  • 3
  • 23
  • 40
  • What's wrong with the code you have? Is there an error in the log? – Brandan Feb 08 '12 at 04:27
  • It's not finding the group_id from the groups table. Giving me an error "undefined method `group_id' for nil:NilClass". I'm not sure if it's a problem with the form or in the controller – Norto23 Feb 08 '12 at 04:46

1 Answers1

1

The reason your code isn't working now is because of this line:

@group = Group.find_by_name(:group)

it should be something like (I don't remember exactly sorry)

@group = Group.find_by_name(params[:membership][:group])

The error is getting called on the next line because @group is nil.

But you should probably handle that type of logic in the model anyway with a virtual attribute or something.

membership.rb

def group_name
  if self.group
    @group_name ||= self.group.name
  end
end

def group_name=(group_name)
  @group_name = group_name

  self.group = Group.find_by_name(@group_name)
end

form

<div class="field">
  <%= f.label :group_name, "Group" %><br />
  <%= f.text_field :group_name %>
</div>

controller

def create
  @membership = current_user.memberships.build(params[:membership])
  if @membership.save
    flash[:notice] = "You have joined this group."
    redirect_to :back
  else
    flash[:error] = "Unable to join."
    redirect_to :back
  end
end
Azolo
  • 4,353
  • 1
  • 23
  • 31
  • excellent, the single line @group = Group.find_by_name(params[:membership][:group]) was exactly what i was looking for thanks – Norto23 Feb 08 '12 at 06:47