从空form_for更新属性

时间:2012-02-01 15:38:07

标签: ruby-on-rails

我希望用户点击按钮在我的发布页面中发布活动。

视图/活动/ 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 

问题是,如何从索引页面获取用户 - &gt;发布页面 - &gt;点击提交 - &gt;更新属性 - &gt;使用flash消息返回Index页面?

1 个答案:

答案 0 :(得分:1)

嗯,我想您正在尝试实现以下工作流程Index page -> Publish page -> click submit -> update the attributes -> 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

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