我正试图each do
在一个表上创建一个新的关系。
规则如下:
我希望current_user
能够参与活动。
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
以用户身份通过join
方法加入活动时,出现了错误的参数错误。
我的按钮如下:
<% Event.all.each do |e| %>
<tr>
<td><%= e.title %></td>
...
<td><%= button_to "join event", join_path e.id, method: :get %></td>
</tr>
<% end %>
路由文件供参考:
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
答案 0 :(得分:1)
我认为您的路线看起来更像(我认为您不需要将其嵌套在users
下):
resources :events do
member do
get :join
end
end
哪个会给你:
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
然后,在您的EventsController
中,执行以下操作:
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
这假定:
class User < ActiveRecord::Base
has_many :attending_events
end
并且:
class AttendingEvent < ActiveRecord::Base
belongs_to :user
belongs_to :event
end
然后在您看来:
<% Event.all.each do |e| %>
<tr>
<td><%= e.title %></td>
...
<td><%= button_to "join event", join_event_path(e), method: :get %></td>
</tr>
<% end %>