本文介绍了如何使用多对多关系帖子#show在Rails中使用ruby的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在团队#模型
class Team < ActiveRecord::Base
has_many :postteams
has_many :posts, :through => :postteams
end
在帖子#模型
class Post < ActiveRecord::Base
has_many :postteams
has_many :teams, :through => :postteams
accepts_nested_attributes_for :postteams
end
在 Postteam模型
class Postteam < ActiveRecord::Base
belongs_to :post
belongs_to :team
end
通过这些关系,我终于成功地在多个团队中任职,并将这些团队保存在数据库中,就像这样
Through these relations, i finally succeed to make post with these multiple teams and also save these teams in database, like this
这是我的 post#controller :
class PostsController < ApplicationController
def index
@posts = Post.all
end
def show
@post = Post.find(params[:id])
end
def new
@post = Post.new
@all_teams = Team.all
@post_team = @post.postteams.build
end
def edit
end
def create
@post = Post.new(post_params)
params[:teams][:id].each do |team|
if !team.empty?
@post.postteams.build(:team_id => 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
现在我被困在这里,如何在 posts#show 页面
Now I'm stuck here, How to show these teams, in posts#show page,
<p>
<strong>Title:</strong>
<%= @post.title %>
</p>
<p>Team Names:</p>
.............what i add here, to show both these multi teams........
推荐答案
仅遍历所有 @post
的 postteams
,并显示其 name
/标题
/其他:
Simply iterate over all @post
's postteams
and display it's name
/title
/whatsoever:
<p>
<strong>Title:</strong>
<%= @post.title %>
</p>
<p>Team Names:</p>
<% @post.postteams.each do |pt| %>
<% = pt.name %> # or whatever attribute of postteam you want to display
<% end %>
</p>
这篇关于如何使用多对多关系帖子#show在Rails中使用ruby的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!