【问题标题】:Custom controller action自定义控制器动作
【发布时间】:2016-09-23 19:44:50
【问题描述】:

我有一个按钮来更改我的 rails 项目中的数据库值:

项目显示视图 (haml)

= link_to("", :controller => "items", :action => "set_active", :id => @item.id) do
    .btn Publish

ItemsController

def show
    @item = Item.find(params[:id])

    def set_active
        @item.is_active = true
        @item.save!

        flash[:notice] = "Item got published"
    end
end

除了按钮之外,视图正常工作。
如果我单击按钮,页面只会刷新,但值不会改变,也不会弹出 flash 消息。

知道为什么吗?

提前感谢每个答案!如果您需要更多信息,请告诉我。

【问题讨论】:

  • 在方法中定义方法 - baaad ;)
  • 您认为我应该怎么做才能实现我的目标? :) 我可以做一个私有方法,但这并不能解决问题......

标签: ruby-on-rails ruby database ruby-on-rails-4 controller


【解决方案1】:

类似的东西:

# controller
def set_active
  @item.is_active = true
  @item.save!

  flash[:notice] = "Item got published"
end

# routes
resources :jobs do
  get :set_active, on: :member
end

# view
link_to 'Activete', set_active_job_path(job)

【讨论】:

  • 非常感谢!我根据您的良好、干净的解决方案找到了一个解决方案:)
猜你喜欢
  • 2016-05-31
  • 2012-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-11
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多