所以,我有一个允许用户创建和查找新事件的应用程序。我想要提取URL,我正在使用this rails casts episode作为参考。
问题在于控制器部分..我的事件控制器中有非常具体的代码,我希望他建议的不会导致任何问题。这是我当前的事件#show action:
def show
@event = Event.where(id: params[:id]).first
if @event.present?
@user = current_user
# @event = Event.find(params[:id])
@owner = @event.user
@participants = @event.participants
@waiting_participants = @event.waiting_participants
else
redirect_to events_path, error: 'Event not found'
end
end
Ryan建议我将查找行更改为:
def show
@event = find_by_slug!(params[:id])
....the rest of my code here
end
正如您所看到的,我发现事件与以下情况略有不同:
def show
@event = Event.where(id: params[:id]).first
....the rest of my code here
end
如何在不弄乱我的代码的情况下开始工作?
干杯!
更新
def update
@event = current_user.events.find(params[:id])
if @event.update_attributes(params[:event])
@event.update_event_date
flash[:success] = "Event updated."
redirect_to @event
else
render 'edit'
end
end
答案 0 :(得分:0)
您的节目视图应该只是“显示”单个项目。你的代码:
@event = Event.where(id: params[:id]).first
......最好表达为:
@event = Event.find(params[:id])
您的原始代码返回包含单个对象的ActiveRecord :: Relation对象(基本上是一个数组)。由于您正在查找具有其ID的对象,该ID在创建记录时自动生成,因此该ID始终是唯一的。
如果你正确地遵循Ryan的演员表,每个唱片都会有一个独特的slug名称。如果你正确地按照他的教程,你的代码应该没问题。