【发布时间】:2015-10-19 17:24:14
【问题描述】:
我在 GIThub 上找到了这个迷你应用程序,它允许用户在这里创建参加和取消活动:https://github.com/ghembo/private-events 唯一的问题是它是为 Rails 3 制作的。我正在尝试将该应用程序实现到我自己的练习应用程序中但到目前为止,我在使用 rails 4.2.4 时遇到了参加活动功能的问题。
我有三个使用富连接连接的模型,其中使用了多个连接:用户、事件和事件注册。
user.rb
class User < ActiveRecord::Base
has_many :event_registrations
has_many :events, through: :event_registrations
.
event.rb
class Event < ActiveRecord::Base
has_many :event_registrations
has_many :users, through: :event_registrations
.
event_registration.rb
class EventRegistration < ActiveRecord::Base
belongs_to :event
belongs_to :user
创建新事件的功能位于 event_registrations_controller.rb 中
class EventRegistrationsController < ApplicationController
def new
EventRegistration.new(event_id: params[:event_id].to_i, user_id:
current_user.id)
redirect_to event_path(params[:event_id])
flash[:notice] = "Thanks for attending this event!"
end
def destroy
EventRegistration.where(event_id: params[:event_id].to_i, user_id:
current_user.id).first.destroy
redirect_to event_path(params[:event_id])
end
private
# Use callbacks to share common setup or constraints between actions.
def set_event_registration
@event_registration = EventRegistration.find(params[:id])
end
def event_registration_params
params.require(:event_registration).permit(:user_id, :event_id)
end
end
这是创建事件的我的 events\show.html.erb 的 sn-p。
<% if session[:user_id] %>
<% if @event.attended_by(User.find(session[:user_id])) %>
<%= link_to "Cancel attendance", event_registration_path(event_id:
@event.id), method: :delete, class: "btn
btn-primary" %>
<% else %>
<%= link_to "Attend", new_event_registration_path(event_id: @event.id),
class: "btn btn-success" %>
<% end %>
<% end %>
问题是我确实收到了“感谢您参加此活动!”消息,但 event_registrations 表中根本没有新记录。
提前感谢您的帮助。
【问题讨论】:
-
您必须有一个创建操作并删除新操作下的 flash_notice。这就是您收到成功消息但没有保存的原因。
-
原作者这样说:“一个用于学习联想的Rails应用”。所以它可能更具实验性。我的建议是不要将它用作您自己系统的基础
-
谢谢@Meier,但我自己只是在练习 Rails,所以这根本不会投入生产。
-
这就是为什么你应该使用一个好的工作示例来学习,而不是一个状态未知且错误未知的实验示例(至少一个)
标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 activerecord