我在Ruby on Rails中创建一个应用程序来存储所玩的足球游戏。
每个用户都必须加入或创建一个联盟,以保持记分板在朋友之间保密。
创建联盟时,我希望创建者自动加入已创建的联赛。
控制器:
class LeaguesController < ApplicationController
before_action :authenticate_user!
def index
@leagues = League.all
end
def new
@league = League.new
@user = User.new
end
def show
@users = User.where(:league_id => current_user.league_id)
find_league
end
def create
@league = League.new(league_params)
@league.league_admin_id = current_user.id
find_user
update_attribute(:user, @league.id)
@user.save(user_params)
if @league.save
redirect_to root_path, :notice => "Successfully created a league"
else
render 'index'
end
end
def edit
find_league
end
def update
find_league
if @leagues.update(league_params)
redirect_to @leagues, :notice => "Successfully editted this league!"
else
render 'edit'
end
end
private
def find_league
@leagues = League.find(params[:id])
end
def find_user
user = User.find(current_user)
end
def league_params
params.require(:league).permit(:league_name, :league_admin_id, :join_key, :league_rules)
end
def user_params
params.require(:user).permit(:league_id)
end
end
所以在创建动作中我通过私有方法find_user寻找current_user,然后我更新了字段league_id,然后我保存了这个值。然而,当创建一个新联盟时,autojoin并没有起作用。我在这里做错了什么?
class League < ActiveRecord::Base
has_many :games
has_many :multiplayergames
has_many :users
belongs_to :league_admin, class_name: 'User', foreign_key: 'league_admin_id'
end
class User < ActiveRecord::Base
belongs_to :league
has_one :league_admin, class_name: 'League', foreign_key: 'league_admin_id'
end
答案 0 :(得分:0)
您的create
操作应如下所示:
def create
@league = League.new(league_params)
if @league.save
current_user.update_attributes(league_id: @league.id)
redirect_to root_path, :notice => "Successfully created a league"
else
render 'index'
end
end
private
def league_params
params.require(:league).permit(:league_name, :league_admin_id, :join_key, :league_rules).merge(league_admin_id: current_user.id)
end