Получение неопределенной локальной переменной или метода "турнир" при использовании гема round_robin_tournament
Я пытаюсь использовать гем round_robin_tournament, как описано:
Однако я получаю ошибку:
неопределенная локальная переменная или метод "турнир" для # <#: 0x00007ffb591d54a0>
Я следовал за описанием в разделе readme этой ссылки. Я все еще новичок в Ruby на рельсах, так что это может быть что-то простое:).
Вот мой код:
Message_Controller.rb:
class MessagesController < ApplicationController
before_filter :authenticate_user!
def create
@conversation = Conversation.find(params[:conversation_id])
@message = @conversation.messages.build(message_params)
@message.user_id = current_user.id
@message.save!
@path = conversation_path(@conversation)
end
private
def message_params
params.require(:message).permit(:body)
end
def tournament
require "round_robin_tournament"
# Compute all the possible teams for each day in the classroom
students = %w(John Paul Ringo George)
teams = RoundRobinTournament.schedule(students)
# Print for each day, each team
teams.each_with_index do |day, index|
day_teams = day.map { |team| "(#{team.first}, #{team.last})" }.join(", ")
puts "Day #{index + 1}: #{day_teams}"
end
# Day 1: (Paul, George), (Ringo, John)
# Day 2: (Ringo, George), (John, Paul)
# Day 3: (John, George), (Paul, Ringo)
end
end
routes.rb:
Rails.application.routes.draw do
resources :posts
resources :comments, only: [:create, :destroy]
devise_for :users
resources :users do
member do
get :friends
get :followers
get :deactivate
get :mentionable
end
end
resources :events do
collection do
get :calendar
end
end
authenticated :user do
root to: 'home#index', as: 'home'
end
unauthenticated :user do
root 'home#front'
end
resources :conversations do
resources :messages
end
match :follow, to: 'follows#create', as: :follow, via: :post
match :unfollow, to: 'follows#destroy', as: :unfollow, via: :post
match :like, to: 'likes#create', as: :like, via: :post
match :unlike, to: 'likes#destroy', as: :unlike, via: :post
match :find_friends, to: 'home#find_friends', as: :find_friends, via: :get
match :about, to: 'home#about', as: :about, via: :get
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
# root 'welcome#index'
# Example of regular route:
# get 'products/:id' => 'catalog#view'
# Example of named route that can be invoked with purchase_url(id: product.id)
# get 'products/:id/purchase' => 'catalog#purchase', as: :purchase
# Example resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Example resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Example resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Example resource route with more complex sub-resources:
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', on: :collection
# end
# end
# Example resource route with concerns:
# concern :toggleable do
# post 'toggle'
# end
# resources :posts, concerns: :toggleable
# resources :photos, concerns: :toggleable
# Example resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
end
index.html.erb:
<div class="row">
<div class="col-lg-3">
<%= render 'shared/user_info' %>
</div>
<div id="newsfeed" class="col-lg-6">
<%= render 'posts/form' %>
<br>
<div id="activities">
<% if @activities.empty? %>
<div class="well">
<%= render('shared/no_resource', resources: 'Activities') %>
</div>
<% else %>
<%= render_activities(@activities, layout: '/shared/activity') %>
<% end %>
</div>
<%= render 'shared/paginate', resources: @activities %>
</div>
<div class="col-lg-3">
<%= render 'shared/links' %>
<% @users.each_with_index do |user, index| %>
<tr>
<td><%= index +=1 %></td>
<td><%= user.name %></td>
<td>
<%= link_to "Send Message", "#", class: "btn btn-success btn-xs start-conversation",
"data-sid" => current_user.id, "data-rip" => user.id %>
</td>
</tr>
<% end %>
</div>
<div>
<%= tournament %>
</div>
</div>
Большое спасибо заранее за помощь.
Новый код:
контроллер:
class MessagesController < ApplicationController
helper_method :tournament
before_filter :authenticate_user!
def create
@conversation = Conversation.find(params[:conversation_id])
@message = @conversation.messages.build(message_params)
@message.user_id = current_user.id
@message.save!
@path = conversation_path(@conversation)
end
# controller
def tournament
require "round_robin_tournament"
RoundRobinTournament.schedule %w(John Paul Ringo George)
end
private
def message_params
params.require(:message).permit(:body)
end
end
Посмотреть:
<div class="row">
<div class="col-lg-3">
<%= render 'shared/user_info' %>
</div>
<div id="newsfeed" class="col-lg-6">
<%= render 'posts/form' %>
<br>
<div id="activities">
<% if @activities.empty? %>
<div class="well">
<%= render('shared/no_resource', resources: 'Activities') %>
</div>
<% else %>
<%= render_activities(@activities, layout: '/shared/activity') %>
<% end %>
</div>
<%= render 'shared/paginate', resources: @activities %>
</div>
<div class="col-lg-3">
<%= render 'shared/links' %>
<% @users.each_with_index do |user, index| %>
<tr>
<td><%= index +=1 %></td>
<td><%= user.name %></td>
<td>
<%= link_to "Send Message", "#", class: "btn btn-success btn-xs start-conversation",
"data-sid" => current_user.id, "data-rip" => user.id %>
</td>
</tr>
<% end %>
</div>
<div>
<% tournament.each_with_index do |day, index| %>
<% day_teams = day.map { |team| "(#{team.first}, #{team.last})" }.join(", ") %>
<%= "Day #{index + 1}: #{day_teams}" %>
<% end %>
</div>
</div>
1 ответ
Это не похоже на то, что это имеет непосредственное отношение к гему, просто методы, определенные в контроллере, по умолчанию недоступны в представлениях. Вы можете указать rails сделать метод доступным для представления, используя helper_method
хоть:
class MessagesController < ApplicationController
helper_method :tournament
# rest of your controller
end
Я не уверен, понравится ли это private
или нет (поэтому, если это не сработает, попробуйте сделать метод public
вместо). Знайте также, что puts
все еще собирается выводить на $stdout
в рельсах, так что если вы хотите вывод в представлении, вы можете просто вернуть teams
из метода, а затем выполните эту итерацию в представлении (не проверено, но, вероятно, будет работать):
# controller
def tournament
require "round_robin_tournament"
RoundRobinTournament.schedule %w(John Paul Ringo George)
end
# view
<% tournament.each_with_index do |day, index| %>
<% day_teams = day.map { |team| "(#{team.first}, #{team.last})" }.join(", ") %>
<%= "Day #{index + 1}: #{day_teams}" %>
<% end %>