in Teams#model
class Team < ActiveRecord::Base
has_many :postteams
has_many :posts, :through => :postteams
end
in Post#model
class Post < ActiveRecord::Base
has_many :postteams
has_many :teams, :through => :postteams
accepts_nested_attributes_for :postteams
end
In Postteam Model
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
here is my 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
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........
Simply iterate over all
@post
'spostteams
and display it'sname
/title
/whatsoever: