我是Rails新手,我正在尝试在我的应用程序中构建以下代码:
签名船长创建一个团队(名称、颜色等),然后在其中添加成员。成员将自动分配到所创建的团队。
我的签名船长在他的个人资料中有一个创建新团队的按钮,它会进入team#new视图。一旦验证了团队表单,就会加载member#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我发现了如何使用devise和current_user在团队表中添加captain_id,但我就是不知道如何在团队创建后处理team_id。我想要在“添加成员”视图中获取team_id值,并处理我的成员控制器以将其与每个成员一起保存。
发布于 2013-12-18 08:23:36
如果您以以下方式组织您的路线,您将可以访问成员页面上的团队和成员详细信息,以及团队页面上的团队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_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发布于 2013-12-19 00:22:50
所以我们有一张包含多个队友的卡片
使用嵌套资源:
routes.rb:
resources :cards do
resources :teammates
endteammate新视图
<%= form_for [@card,@teammate] do |f| %>
...
<% end %>Teammate控制器
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过滤器: before_filter :require_card private def require_card @teammate = Teammate.find(params:id) end
但它给我带来了错误,所以我放弃了它
如果有适当的方法来做这件事/提高我的学习水平,我很想知道它们,所以请随时给我提供线索。
谢谢!
https://stackoverflow.com/questions/20647034
复制相似问题