繁体   English   中英

如何使用多对多关系帖子#show在Rails中使用ruby

[英]How to use Many to Many Relationship posts#show In ruby on rails

Teams#model中

class Team < ActiveRecord::Base

  has_many :postteams
  has_many :posts, :through => :postteams

end

Post#model中

class Post < ActiveRecord::Base

  has_many :postteams
  has_many :teams, :through => :postteams

  accepts_nested_attributes_for :postteams
end

后期团队模型中

class Postteam < ActiveRecord::Base
  belongs_to :post
  belongs_to :team
end

通过这些关系,我终于成功地在多个团队中任职,并将这些团队保存在数据库中,就像这样

1

这是我的帖子#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页面中显示这些团队

<p>
  <strong>Title:</strong>
  <%= @post.title %>
</p>

<p>Team Names:</p>

.............what i add here, to show both these multi teams........

2

只需遍历所有@postpostteams并显示其name / title /任何内容:

<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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM