简体   繁体   English

Rails-在联接表中创建/销毁记录

[英]Rails - Create/Destroy record in join table

I'm working on this record insert/delete I'm not sure what the syntax is to perform the query. 我正在处理此记录的插入/删除,我不确定执行查询的语法是什么。

I have a user model and an event model. 我有一个用户模型和一个事件模型。 I have created a joining table called Personal that stores the user_id, and event_id of any events that the users like. 我创建了一个名为Personal的联接表,该表存储user_id和用户喜欢的任何事件的event_id。

I created an "Add" method in my events controller so whenever someone clicks it run to that and perform the create logic I'm trying to develop now.The action is tied to a extra column I added to the grid displaying all the events. 我在事件控制器中创建了一个“添加”方法,因此每当有人单击它时,它就会运行并执行我现在要开发的创建逻辑。该操作与我添加到网格中显示所有事件的额外列相关。

The user model => 用户模型=>

 has_many :personals

The event model => 事件模型=>

has_many :personals

The personal model => 个人模特=>

belongs_to :user
belongs_to :events

I thought it would be something like => 我以为那会是=>

 @user = User.find(session[:user_id])
 @event = Event.find(params[:id])
 # Personal.new = User.Event?

can anyone help? 有人可以帮忙吗?

If you're using a has_and_belongs_to_many association, which would be unfortunate, removing the associated links can be tricky as there's no identifier for each link. 如果您使用的是has_and_belongs_to_many关联(很不幸),则删除关联的链接可能会很棘手,因为每个链接都没有标识符。

Using a has_many :through relationship is much easier to maintain and will allow you to do simple things like: 使用has_many :through关系更容易维护,并且可以执行以下简单操作:

class User < ActiveRecord::Base
  has_many :user_events
  has_many :events,
    :through => :user_events
end

@user.events.delete(@event)

This doesn't remove the Event itself, that'd require an Event#destroy call, but the join record that links the two. 这不会删除Event本身,而需要Event#destroy调用,但是会删除链接两者的联接记录。

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

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