Ruby on rails 如何在Rails中创建联接表记录,有很多:通过关系
类user和event具有has-many:throughrelationshipRuby on rails 如何在Rails中创建联接表记录,有很多:通过关系,ruby-on-rails,ruby,Ruby On Rails,Ruby,类user和event具有has-many:throughrelationship class User < ActiveRecord::Base has_many :user_events has_many :events, :through => :user_events end class Event < ActiveRecord::Base has_many :user_events has_many :users, :through => :u
class User < ActiveRecord::Base
has_many :user_events
has_many :events, :through => :user_events
end
class Event < ActiveRecord::Base
has_many :user_events
has_many :users, :through => :user_events
end
这感觉很重,所以我想有一个更好的,更适合Rails的方法。正确的方法是什么?这取决于参数带来的内容以及它们的格式。如果它是一个表单提交,并且它带来了一个用户id,那么您应该能够创建事件
def create
@event = Event.new(event_params)
if @event.save
@event.users << current_user
redirect_to event_path(@event)
else
render action: :new
end
end
user=user.findparams[:user\u id]
user.events这取决于参数带来的内容及其格式。如果它是一个表单提交,并且它带来了一个用户id,那么您应该能够创建事件 user=user.findparams[:user\u id]
user.events有关扩展响应,请参阅https://stackoverflow.com/questions/7297338/how-to-add-records-to-has-many-through-association-in-railsanswer-18114492for 延伸的回应,看见https://stackoverflow.com/questions/7297338/how-to-add-records-to-has-many-through-association-in-railsanswer-18114492I 我喜欢这个答案,但我得到了一个错误:未定义的方法'add'表示Ok。尝试新的答案。我猜错了,您在当前用户中有一个用户实体。我喜欢这个答案,但我得到了一个错误:未定义Ok的方法'add'。尝试新的答案。我猜错了,您在当前用户中有一个用户实体。
def create
@event = Event.new(event_params)
if @event.save
@event.users << current_user
redirect_to event_path(@event)
else
render action: :new
end
end
def create
@event = Event.new(event_params)
@event.users.add(User.find(current_user.id))
@event.save # I guess that you want to save the relation
end
current_user.events << Event.new(params[:event])