MKK
MKK

Reputation: 2753

ruby on rails form and passing its parameter to controller

When the view pass the parameters to controller, controller gets nil for all of the arguements somehow.

Can anyone how to fix this?? Thanks!

and I have no model called "Message"

controllers/messages_controller.rb

  def deliver

   recipient = User.find_by_username(params[:recipient])
   subject = params[:subject]
   body = params[:body]

   current_user.send_message(recipient, body, subject)
    redirect_to :controller => 'messages', :action => 'received' 
    flash[:notice] = "message sent!"

  end

views/messages/new.html.erb

<%=form_for :messages, url: url_for( :controller => :messages, :action => :deliver ) do |f| %>
    <div class="field">
      <%= f.label :subject %><br />
      <%= f.text_field :subject %>
    </div> 

    <div class="field">
      <%= f.label :body %><br />
      <%= f.text_field :body %>
    </div> 

  <div class="actions">
    <%= f.submit %>

<% end %>

Upvotes: 1

Views: 12431

Answers (2)

Ganesh Kunwar
Ganesh Kunwar

Reputation: 2653

You can get parameter value using
datas = params[:messages]
These values are in array form. So you can fetch array datas If you want to individual data then use
subject = datas[:subject]
body = datas[:body]

To check run following code in view
<%= subject %>
this gives the value of subject.

Upvotes: 1

Wawa Loo
Wawa Loo

Reputation: 2276

Check your source HTML to better understand what FormHelpers do.

With the form_for f.text_field will generate names attributes in the format:

messages[subject]

Consequently, your params will be in the format:

params[:messages][:subject]

You can also use <%= debug params %> to inspect what's in params, it's very helpful.

Upvotes: 9

Related Questions