Bill W.
Bill W.

Reputation: 47

Ruby on rails adding users to groups

I am building a social networking site with user, school, and schoolgroup models. The users join, and have different roles in, the schools through the has_many through schoolgroups. I am having trouble writing an online form_for button that a user can click on to apply to the school. The params I need to be included in the creation of the schoolgroup object are the user_id, the school_id, and the role 'applicant'. I know that I can use current_user.schoolgroups.build to have the form initialize a create action and include the correct user_id, but the problem I am having is how to write a form which sends the school_id to the controller to create the new schoolgroup object. The @school instance variables in my code are just placeholders for whatever the correct code should be

def create
  @school = School.find(params[:schoolgroups][:school_id)
  current_user.schoolgroups.build(school_id: @school.id, user_id: current_user.id, role: 'applicant')
  respond_with school_path
 end

<%= form_for( current_user.schoolgroups.build(params[school_id: @school.id]), 
                                                       remote: true) do |f| %>
  <div><%= f.hidden_field :school_id %></div>
   <%= f.submit "Apply", class: "btn btn-large btn-primary" %>
   <% end %>

Upvotes: 0

Views: 1251

Answers (1)

Maxime Garcia
Maxime Garcia

Reputation: 610

I'd go this way

# in routes
resources :schools do
  member do
    put :apply
  end
end

# in schools_controller.rb
def apply
  @school = School.find(params[:id])
  @schoolgroup = current_user.schoolgroups.create(school: @school, role: 'applicant')
  respond_with @schoolgroup
end

#in your view
<%= link_to "Apply", apply_school_path(@the_school_var_you_define_somewhere), remote: true, method: :put,
  class: "btn btn-large btn-primary" %>

This is simplier, and more in the Rails spirit.

Upvotes: 1

Related Questions