Rails运行:在/ new和/ edit _form中获取路由

时间:2017-03-22 14:03:33

标签: ruby-on-rails rest routes render

_form new edit@Giveaway对象giveaways#random_winner。在这个表格中,我有一个随机赢家的字段。

我想通过使用<%= button_to "Randomly Pick Winner!", {:action => 'choose_winner'}, :method => :get %>调用方法No route matches {:action=>"choose_winner", :controller=>"giveaways"}来填充此字段,但是在加载/giveaways/new时收到此错误 def choose_winner random_winner = SubscriberUser.where(user_id: current_user.id).pluck(:subscriber_id).sample(1) session[:random_winner] = random_winner redirect_to :back end

这是我的控制器:

  resources :giveaways do
    member do        
      get 'choose_winner' => 'giveaways#choose_winner'
      #tried get :choose_winner, as: :choose_winner
      #tried get 'new/choose_winner'
      #tried get 'choose_winner'
      #tried get 'choose_winner', to: 'giveaways#choose_winner', as: 'choose_winner'
    end
  end

以下是我尝试过的路线。我还不擅长非脚手架路线:

public function initialize(array $config)
{
    parent::initialize($config);

    $mailer = new UserMailer(); //use App\Mailer\UserMailer;
    $this->eventManager()->on($mailer);

    //more code...
}

问题 - 当我在路线中定义控制器和操作时,为什么页面没有加载?当我运行该路线时,是否必须重新加载页面...是否有更好的方法来获取此数据?

1 个答案:

答案 0 :(得分:1)

您的routes.rb已关闭

resources :giveaways do 
  member do
    get :choose_winner
  end
end

然后我会使用Rails路由助手,这样您就不必担心自己设置动作/控制器了。

<%= button_to "Randomly Pick Winner", choose_winner_giveaway_path(@giveaway), method: :get %>