简体   繁体   English

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

[英]Ruby on Rails HABTM association doesn't update join table

I've a many-to-many association of Tags and Users. 我有一个标签和用户的多对多关联。 when I create a tag my join-table doesn't update, I think there's something with the controller.. 当我创建标签时,我的联接表没有更新,我认为控制器有问题。

tag model 标签模型

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

user model 用户模型

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

You're never joining together the created tag and the current user from what I can see. 从我所看到的情况来看,您永远不会将创建的tag和当前用户联系在一起。

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

Also, usually the argument of has_and_belongs_to_many is pluralized, eg has_and_belongs_to_many :users 同样,通常has_and_belongs_to_many的参数是复数的,例如has_and_belongs_to_many :users

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

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