pwz2000
pwz2000

Reputation: 1395

How to refer to method inside form

I added a askout method to the controller, which is a duplicate of the create method with a slight change.

I need help referencing the new method in the form in the view. I can only get it to send messages using the create and new method from the controller.

Messages controller:

  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'

Routes:

  resources :messages
  member do
    post :askout

Upvotes: 0

Views: 30

Answers (2)

xps15z
xps15z

Reputation: 1829

Below changes will accomplish what you're looking for.

Routes:

resources :messages do
  member do
  post :askout
  end
end

View:

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

Controller:

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

Upvotes: 1

Eugene Tkachenko
Eugene Tkachenko

Reputation: 232

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

And also update your routes file:

resoucres :members do
  member do
  post :askout
  end
end

Upvotes: 0

Related Questions