【问题标题】:Updates attributes from an empty form_for从空的 form_for 更新属性
【发布时间】:2012-02-02 01:31:09
【问题描述】:

我希望用户单击按钮以在我的发布页面中发布事件。

views/events/publish.html.erb

<%= form_for @event do |p| %>       
   <%= p.submit "Yes publish my event now" %> | 
   <%= link_to "Cancel", events_path %>
<% end %>

用户可以从我的索引页面进入发布页面

视图/事件/index.html.erb

<% for event in @events %>
   <%= link_to "Publish", publish_path(:id => event) %>
<% end %>

Publish_path 已在路由中定义为事件控制器

routes.rb

match 'publish' => 'events#publish', :as => :publish

这是我的事件控制器

events_controller.rb

def publish
  @event = Event.find(params[:id])
end

当我在发布操作中添加代码(见下文)以更新事件模型时,控制器将更新属性,但当用户单击我的索引中的发布链接时。

使用此代码的用户在点击索引中的发布链接时看不到我的发布页面。相反,它们将被发送回索引页面,但所有属性都会更新。

def publish
   @event = Event.find(params[:id])
   if @event.update_attributes(:published_at => DateTime.now, :publish => true)
     flash[:success] = "Your event has been publish"
     redirect_to events_path
   end
end 

问题是,我如何从索引页面获取用户 -> 发布页面 -> 点击提交 -> 更新属性 -> 返回到索引页面并显示 Flash 消息?

【问题讨论】:

  • +1 了解详细信息,但你能再解释一下这个问题吗?发生了什么你不想发生的事情?
  • 索引页是什么意思?您的EventsControllerindex 操作?您是否在该页面上显示闪光灯?
  • 目前正在发生的是索引页面 -> 点击链接转到发布页面 -> 属性更新 -> 索引页面。

标签: ruby-on-rails


【解决方案1】:

我猜你正在尝试实现以下工作流程,Index page -&gt; Publish page -&gt; click submit -&gt; update the attributes -&gt; return back to Index page with flash message

我们不能同时使用一个动作来实现,所以再添加一个动作

events_controller

# Will take user to confirm page, where we display the form with "Yes publish now" and "cancel" button
def confirm_publish
  @event = Event.find(params[:id])
end

# When user clicks the "yes publish now" button, request should come here and perform the same.
def publish
  @event = Event.find(params[:id])
  if @event.update_attributes(:published_at => DateTime.now, :publish => true)
    flash[:success] = "Your event has been publish"
    redirect_to events_path
  end
end

相应地我们需要修改视图和路由。

【讨论】:

  • 在我的 confirm_publish.html.erb 中添加了&lt;%= form_for @event, url =&gt; {:action =&gt; 'publish'}, do |p| %&gt;。但后来它说No route matches {:action=&gt;"publish", :controller=&gt;"events"} 我已经在我的routes.rb 中有resources :events。我错过了什么?
猜你喜欢
  • 2012-03-11
  • 2018-09-23
  • 2016-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多