blkpingu
blkpingu

Reputation: 1676

wrong number of arguments (given 0, expected 1)

What I'm trying to do

I'm trying to each do over a table to create a new relationship.

The rules are as follows:

I want current_user as per devise gem to be able to join events.

What I tried

class AttendingEventsController < ApplicationController

  def new
    @attending_event = AttendingEvent.new
  end

  def join event_id
    @attending_event = @attending_event.new(user_id: current_user.id, event_id: event_id)
  end
end

When joining the event via the join method as user I'm getting the wrong arguments error.

My button looks like this:

<% Event.all.each do |e| %>
      <tr>
        <td><%= e.title %></td>
        ...
        <td><%= button_to "join event", join_path e.id, method: :get %></td>
      </tr>
<% end %>

Routes file for reference:

Rails.application.routes.draw do
  devise_for :users
  get 'welcome/home'
  get 'events/all'
  get 'users/index'

  get '/join', to: 'attending_events#join', as: 'join'


  resources :users do
    resources :events
  end

  root 'welcome#home'
end

Upvotes: 0

Views: 1308

Answers (1)

jvillian
jvillian

Reputation: 20263

I would think that your routes would look something more like (I don't think you need to nest it under users):

resources :events do 
  member do 
    get :join
  end
end

Which will give you:

join_event GET    /events/:id/join(.:format)                             events#join
    events GET    /events(.:format)                                      events#index
           POST   /events(.:format)                                      events#create
 new_event GET    /events/new(.:format)                                  events#new
edit_event GET    /events/:id/edit(.:format)                             events#edit
     event GET    /events/:id(.:format)                                  events#show
           PATCH  /events/:id(.:format)                                  events#update
           PUT    /events/:id(.:format)                                  events#update
           DELETE /events/:id(.:format)                                  events#destroy

Then, in your EventsController, do:

class EventsController < ApplicationController

  def new
    # I don't know if you need this, based on the code you posted
    @attending_event = AttendingEvent.new
  end

  def join
    @event = Event.find(params[:id])
    @attending_event = current_user.attending_events.new(event: @event)
    if @attending_event.save
      #do something
    else
      #do something else
    end
  end

end

This assumes that:

class User < ActiveRecord::Base 
  has_many :attending_events
end

And:

class AttendingEvent < ActiveRecord::Base
  belongs_to :user
  belongs_to :event
end

Then in your view:

<% Event.all.each do |e| %>
  <tr>
    <td><%= e.title %></td>
    ...
    <td><%= button_to "join event", join_event_path(e), method: :get %></td>
  </tr>
<% end %>

Upvotes: 1

Related Questions