Ruby on Rails HABTM关联不更新连接表

时间:2012-02-25 03:57:57

标签: ruby-on-rails associations has-and-belongs-to-many

我有一个多对多的标签和用户关联。 当我创建一个标签时,我的连接表不会更新,我认为控制器有一些东西..

标签模型

class Tag < ActiveRecord::Base
  validates :tag, :presence => true
  has_and_belongs_to_many :user, :join_table => "tags_users"
end

用户模型

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

  attr_accessible :email, :password, :password_confirmation,:remember_me

  has_and_belongs_to_many :tag, :join_table => "tags_users"
end

tags_controller

class TagsController < ApplicationController
  before_filter :authenticate_user!, :except => [:index, :show]

  def create
    @tag = Tag.new(params[:tag])

    respond_to do |format|
      if @tag.save
        format.html { redirect_to tags_path, notice: 'Tag was successfully created.' }
        format.json { render json: @tag, status: :created, location: @tag }
      else
        format.html { render action: "new" }
        format.json { render json: @tag.errors, status: :unprocessable_entity }
      end
    end
  end
end

1 个答案:

答案 0 :(得分:1)

您永远不会将我所看到的创建的tag和当前用户联系在一起。

@tag = Tag.new(params[:tag])
@tag.users << current_user

此外,通常has_and_belongs_to_many的参数是多元的,例如has_and_belongs_to_many :users