Search code examples
ruby-on-railsmodelinvite

Rails, updating records for an invitation system


I want to allow users to accept invitations, the accept tag is in the invite model itself (so I need to update the table). So far nothing occurs when the user clicks the accept button

View

 <% @invites.where(user_id: current_user.id).find_each do |invite| %>
...
 <%= button_to "Accept", accept_invite_invites_path(invite), method: :put %>
 end

Routes

  resources :invites do
    collection do
      get 'accept_invite'
    end
  end

Controller

def accept_invite

  @invite = Invite.find(params[:id])
  @invite.accept
end

def decline_invite
  @invite = Invite.find(params[:id])
  @invite.decline
end

    def set_invites
      @invite = @story.invites.find(params[:id])
    end

 def new
    @invite = @story.invites.new
 end

I get "undefined method `invites' for nil:NilClass" if I keep :update as a part of set_invites, removing update allows my code to run, but no changes to the database is made.

Model

   def accept
    accept = true
    save

  end

  def decline
    accept = false
    save

  end

Console

Processing by InvitesController#update as 
  Parameters: {"authenticity_token"=>"BDle9fqXHT9ZFctMbO4RvxfPuTQXe2Nq+b6/T29B3xjpYdtMozVUFLiRlaQFtuYzMrBceTQn8OtfGjJTe4wa/Q==", "id"=>"accept_invite"}
  User Load (1.7ms)  SELECT  `users`.* FROM `users` WHERE `users`.`id` = 2 ORDER BY `users`.`id` ASC LIMIT 1
No template found for InvitesController#update, rendering head :no_content
Completed 204 No Content in 85ms (ActiveRecord: 1.7ms)

It's weird because the database is selecting from the user table rather than updating the invites table

So what is the problem? Is the route faulty? My set_invites method?


Solution

  • So what is the problem? Is the route faulty? My set_invites method?

    Yes,your route is faulty. As I can see you declared your route on a collection, but you need it on a member. And also you should change it to put.

    resources :invites do
      member do
        put 'accept_invite'
      end
    end