如何在表单内部引用方法

时间:2014-09-16 16:51:30

标签: ruby-on-rails

我向控制器添加了askout方法,这是create方法的副本,略有变化。

我需要帮助在视图中引用表单中的新方法。我只能使用控制器中的createnew方法发送消息。

消息控制器:

  def new
    @message = current_user.messages.new
  end

  def create
    @recipient = User.find(params[:user])
    current_user.send_message(@recipient, params[:body], params[:subject])
    flash[:notice] = "Message has been sent!"
    redirect_to :conversations
  end

  def askout
      @recipient = User.find(params[:user])
      current_user.send_message(@recipient, "Let's go...#{@body}", params[:subject])
      flash[:notice] = "Message has been sent!"
      redirect_to :conversations
    end

show.html.slim:

#ask_me.mfp-hide 
          center
            .message_div
              = form_tag messages_path, method: :post, remote: true, class:'form-horizontal',id: 'message_form', role: 'form'
                = hidden_field_tag :user, @user.id
                .form-group
                  = hidden_field_tag :subject, "#{@current_user} messaged you", class: 'form-control' 
                .form-group
                  = label_tag :body, 'Your Message', class: 'control-label'
                  = text_area_tag :body, nil, placeholder: "Hi, I like your picture and figured I should write you a message and say...", class: 'form-control' 
                br
                = submit_tag 'Send Message', class: 'btn btn-primary'

路线:

  resources :messages
  member do
    post :askout

2 个答案:

答案 0 :(得分:1)

以下更改将完成您正在寻找的内容。

路线:

resources :messages do
  member do
  post :askout
  end
end

查看:

          = form_tag url_for(:controller => 'messages', :action => 'askout'), :method => 'post'

控制器:

  current_user.send_message(@recipient, "Let's go...#{params[:body]}", params[:subject])

答案 1 :(得分:0)

form_for @recipient, :url => url_for(:controller => 'messages', :action => 'askout')

并且还更新您的路线文件:

resoucres :members do
  member do
  post :askout
  end
end