I'm new in Rails. I try to make a list of groups (/groups) where I want to have edit and delete option in each row. Editing should be implemented by modal because Group has only one attribute - name. So I don't want to open /groups/number/edit.
My problem is: I don't know how to bind chosen group with form_for. Maybe it isn't good approach indeed. Modal is displayed, but the name field is blank. When I used debug for @group is blank too. I don't know why.
Here is my code(single group row):
<li id="group-<%= group.id %>" class="list-group-item"> <span class="group-name"><%= group.name %></span> <%= link_to edit_group_path(group.id), "data-toggle" => "modal", "data-target" => "#myModal", :class => "edit-option btn" do %> <i class="fa fa-pencil-square-o fa-2x" ></i> <% end %> <%= link_to group, method: :delete, data: { confirm: "Na pewno chcesz usunąć tę grupę?" }, :class => "delete-option btn btn-danger" do %> <i class="fa fa-trash-o" > usuń</i> <% end %> <!-- Modal --> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button> <h4 class="modal-title" id="myModalLabel">Zmień nazwę grupy</h4> </div> <%= form_for(@group) do |f| %> <div class="modal-body"> <%= debug @group %> <p> <%= f.label :name, "Nazwa" %> <%= f.text_field :name, class: 'form-control'%> </p> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Anuluj</button> <%= f.submit "Zapisz zmiany", class: "btn btn-primary" %> </div> <% end %> </div> </div> </div> Controller
def edit @group = current_user.groups.find_by(id: params[:id]) end def update @group = current_user.groups.find_by(id: params[:id]) if @group.update_attributes(group_params) flash[:success] = "Nazwa grupy została zmieniona" redirect_to groups_path else redirect_to groups_path end end
Group.find(params[:id])- it will throw an exception in such case.GET /groups/:id/editredirects to action edit of groups controller passing params[:id]. This action is used for editing already existing groups. In your case either the group with given id not exist at all or does not belong to current_user and this is the reason, that @group is nil.@groups.each dolooping?