我已经完成了这里的所有操作http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association,但它不起作用。我在stackoverflow中找到了一些答案,但它仍然不起作用。我已经为海报和类型建立了关联。但是当我指定海报的类型时,什么也没有发生。没有添加到数据库,也没有类型在海报的视图中。这是我的 PostrsTypes 创建表:
class PostersTypes < ActiveRecord::Migration
def change
create_table :posters_types, id: false do |t|
t.integer :poster_id
t.integer :type_id
end
add_index :posters_types, [:poster_id, :type_id]
end
end
这是海报模型:
class Poster < ActiveRecord::Base
has_and_belongs_to_many :types
belongs_to :user
validates :title, :body, :publish_date, :user_id, :presence => true
end
和类型模型:
class Type < ActiveRecord::Base
has_and_belongs_to_many :posters
validates :name, :presence => true
end
任何想法为什么什么都没有写入数据库?
编辑。那是我的 posters_controller,如果你需要它:
class PostersController < ApplicationController
before_action :set_poster, only: [:show, :edit, :update, :destroy]
before_filter :authenticate_user!, :except => :index
# GET /posters
# GET /posters.json
def index
@posters = Poster.all
end
# GET /posters/1
# GET /posters/1.json
def show
end
# GET /posters/new
def new
@poster = Poster.new
end
# GET /posters/1/edit
def edit
end
# POST /posters
# POST /posters.json
def create
@poster = Poster.new(poster_params)
@poster.user_id = current_user.id
respond_to do |format|
if @poster.save
format.html { redirect_to @poster, notice: 'Poster was successfully created.' }
format.json { render action: 'show', status: :created, location: @poster }
else
format.html { render action: 'new' }
format.json { render json: @poster.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /posters/1
# PATCH/PUT /posters/1.json
def update
respond_to do |format|
if @poster.update(poster_params)
format.html { redirect_to @poster, notice: 'Poster was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @poster.errors, status: :unprocessable_entity }
end
end
end
# DELETE /posters/1
# DELETE /posters/1.json
def destroy
@poster.destroy
respond_to do |format|
format.html { redirect_to posters_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_poster
@poster = Poster.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def poster_params
params.require(:poster).permit(:title, :body, :publish_date, :type_ids)
end
end