RAILS3: Pass arbitrary parameters via button_to?

后端 未结 5 1941
北海茫月
北海茫月 2020-12-30 04:02

I\'m trying to do something very simple in my first Rails app (Rails 3) and I\'m not sure what I\'m doing wrong, or if there\'s a better approach. Can\'t find anything on th

相关标签:
5条回答
  • 2020-12-30 04:15

    Just circling back to finish this up. Ultimately I solved this by using link_to but using jQuery to make it look like a button. @kishie, if you're saying you made this work with button_to I'd like to see the code, but as I like jQuery it's solved as far as I'm concerned (for this app, anyway.)

    Here's the code in Article#show view. (The class is what makes it look like a button via jQuery.)

    <%= link_to "New Request", new_work_request_path(:article_id => @article.id), :class => "ui-button" %>
    

    Here's the code in Work_Request controller's new method:

    if !params[:article_id].blank?
      @work_request.article = Article.find(params[:article_id])
    end
    

    Then the Work_Request#new view renders it properly.

    0 讨论(0)
  • 2020-12-30 04:29

    I just hit a similar issue and I got it to work by passing the parameter as follows:

    <%= button_to("Add WorkRequest", new_work_request_path(:article_id => @article.id), :action => "new", :method => :get)%>
    
    0 讨论(0)
  • 2020-12-30 04:36

    In article#show

    <%= button_to("Add WorkRequest", {:controller => "work_request", :action => "new", :article_id => @article.id})%>

    In work_requests#new

    <%= f.text_field :article_id, :value => params[:article_id]%>

    0 讨论(0)
  • 2020-12-30 04:39

    If you nest your resources for :work_requests within :articles in your routes.rb, then pass your params[:id] which would be your article_id and add :method => :get to the button_to call, you should be okay.

    # config/routes.rb
    resources :articles do
      resources :work_requests
    end
    
    # app/views/articles/show.html.erb
    <%= button_to "Add Work Request", new_article_work_request_path(params[:id]), 
        :method => :get %>
    
    # app/controllers/work_requests_controller.rb
    class WorkRequestsController < ApplicationController
    
      ...
      def new
        @work_item = WorkItem.new
        @article = Article.find(params[:article_id])
        ...
      end
    
      ...
    end
    
    0 讨论(0)
  • 2020-12-30 04:40

    Add this line of code in your routes.rb file.

    resources :work_requests do
      member do 
        post 'new'
      end
    end
    

    It shouldn't be the GET method because you're sending information to the server, via :module_id. This will then work.

    <%= button_to("Add WorkRequest", {:controller => "work_request", :action => "new", :article_id => @article.id})%>
    
    0 讨论(0)
提交回复
热议问题