I've got project and user models with belongs_and_has_many in them. Now I need add specific user into project's collection. I've got method in projects controller:
def addfriend
@project = Project.find(params[:id])
@project.users << User.find(params[:user])
respond_to do |format|
format.html { redirect_to project, :notice => 'Added.' }
end
end
and I've got this code in show.html.erb of project:
<select id="user_select" name="user_select" class="input-large">
<% @users.each do |user| %>
<option><%= user.username %></options>
<% end %>
</select>
<!-- button to addfriend method here -->
Now, I need to add button on mark in code (or somewhere else) with calling that "addfriend" method.
In routes.rb I've got:
resources :projects do
collection do
get :addfriend
end
end
Assuming you have an @project variable defined somewhere:
<%= link_to 'Add friend', addfriend_project_path(@project, user_id: user.id) %>
In your Projects controller action change the 2 firsts lines for this:
project = Project.find(params[:id])
@project.users << User.find(params[:user_id])
And in your routes:
resources :projects do
member do
get :addfriend
end
end