如何使用多对多关系post#show在ruby on rails
在团队#model中
class Team :postteams end
在Post#model中
class Post :postteams accepts_nested_attributes_for :postteams end
在Postteam模型中
class Postteam < ActiveRecord::Base belongs_to :post belongs_to :team end
通过这些关系,我终于成功发布了这些多个团队,并将这些团队保存在数据库中,就像这样
1
这是我的post#controller :
class PostsController team) end end respond_to do |format| if @post.save format.html { redirect_to @post, notice: 'post was successfully created.' } format.json { render :show, status: :created, location: @post } else format.html { render :new } format.json { render json: @post.errors, status: :unprocessable_entity } end end end def update respond_to do |format| if @post.update(post_params) format.html { redirect_to @post, notice: 'post was successfully updated.' } format.json { render :show, status: :ok, location: @post } else format.html { render :edit } format.json { render json: @post.errors, status: :unprocessable_entity } end end end def destroy @post.destroy respond_to do |format| format.html { redirect_to post_url, notice: 'Player was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_player @post = Post.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def post_params params.require(:post).permit(:title, team_ids: []) end end
现在我被困在这里,如何展示这些团队 ,在post#show page,
Title:
Team Names:
.............what i add here, to show both these multi teams........
2
简单地遍历所有@post
的后postteams
并显示它的name
/ title
/ postteams
:
Title: <%= @post.title %>
Team Names:
<% @post.postteams.each do |pt| %> <% = pt.name %> # or whatever attribute of postteam you want to display <% end %>