我是Rails的新手,我正在尝试在我的应用程序中构建它:
签名队长创建一个团队(名称、颜色等),然后在其中添加成员。成员将自动分配给创建的团队。
我的签名队长在他的个人资料上有一个创建新团队的按钮,它会进入团队#新视图。验证团队表单后,将加载成员#new,以便将成员逐一添加到团队中。
我建立了模型关系:
Captain:
has_many :teams
has_many :members through :team
Team:
belongs_to :captain #captain_id
has_many :members
Member:
belongs_to :team #team_id
has_one :captain
我发现了如何使用design和current_user在团队表中添加captain_id,但我不知道如何在团队创建后处理team_id。我想在"添加成员"视图中获得team_id值,并处理我的成员控制器以将其与每个成员一起保存。
如果您以以下方式构建路线,您将可以访问成员页面上的团队和成员详细信息,以及团队页面上的球队id:
# config/routes.rb
resources :teams do
resources :members
end
# uncomment to have members viewable when not associate with a team in the url
# resources :members
您可以使用命名路由路由到团队:teams_path
、team_path(@team)
会员:team_members_path(@team)
、team_member_path(@team, @member)
在teams_controller中,当提供团队id时,您将可以访问params[:id]
。例如,在url /teams/1
中,params[:id]
将保存值1
。
在成员控制器中,您将有params[:team_id]
,params[:id]
将保存成员id。
例如:
# app/controllers/teams_controller.rb
def show
@team = Team.find params[:id]
end
# app/controllers/members_controller.rb
def index
# finds the team and pre-loads members in the same query
@team = Team.includes(:members).find(params[:team_id])
end
# /teams/1/members/2
def show
@member = Member.find params[:id]
end
所以我们有一张包含多个队友的卡片
使用嵌套资源:
routes.rb:
resources :cards do
resources :teammates
end
队友新视图
<%= form_for [@card,@teammate] do |f| %>
...
<% end %>
队友控制器
def index
@card = Card.includes(:teammates).find(params[:card_id])
@teammates = Teammate.all
end
# GET /teammates/1
# GET /teammates/1.json
def show
@teammate = Teammate.find(params[:id])
end
# GET /teammates/new
def new
@card = Card.find(params[:card_id])
@teammate = Teammate.new
end
# GET /teammates/1/edit
def edit
@teammate = Teammate.find(params[:id])
end
# POST /teammates
# POST /teammates.json
def create
@card = Card.find(params[:card_id])
@teammate = Teammate.new(teammate_params)
@teammate.card_id = params[:card_id]
respond_to do |format|
if @teammate.save
format.html { redirect_to @teammate, notice: 'Teammate was successfully created.' }
format.json { render action: 'show', status: :created, location: @teammate }
else
format.html { render action: 'new' }
format.json { render json: @teammate.errors, status: :unprocessable_entity }
end
end
end
我试图在成员控制器中放入一个前置过滤器:before_filter:require_card私有的def require_card@队友=队友.fund(params[:id])结束
但它给我带来了错误,所以我放弃了
如果有合适的方法来完成这个技巧/提高我的学习,我很想了解他们,所以请随时给我线索。
谢谢!