Reputation: 435
I am trying to send a message to another user. But when I leave a field blank, the controller renders another 'new' action.
Here is the view code that links to the first submit:
<%= link_to 'Send Mail', {:controller => 'messages', :action => 'new', :recipient_id => @profile.id}, :class => 'btn btn-large btn-primary' %>
Here is the message#new code:
def new
@message = Message.new
@recipient = Profile.find(params[:recipient_id])
end
Here is the message#new view code:
<%= simple_form_for @message do |f| %>
<%= f.input :title %>
<%= f.input :body %>
<%= f.input :recipient_id, :as => :hidden, :input_html => {:value => @recipient.id} %>
<%= f.input :sender_id, :as => :hidden, :input_html => {:value => @recipient.id} %>
<%= f.button :submit %>
<% end %>
Here is the message#create code:
def create
@message = Message.new(params[:message])
if @message.save
flash[:notice] = "New message created"
redirect_to @message
else
flash[:error] = "Did not work"
@recipient = params[:recipient_id]
render action: "new"
end
end
How do I get the :recipient_id value submitted in the form and pass into the render new action?
Upvotes: 0
Views: 404
Reputation: 460
When you rendering new
method rails won't execute it codes instead it only renders the view(new.html.erb) of the new
action and you already generating
a recipient_id
which is enough for your form to pass the parameter
Try this
def create
@message = Message.new(params[:message])
if @message.save
flash[:notice] = "New message created"
redirect_to @message
else
flash[:error] = "Did not work"
@recipient = Profile.find(params[:message][:recipient_id])
render action: "new"
end
end
When rendering the new
action we have to create the instances manually which is used in the view.
Note: If you want generate a new parameter use redirect_to
method, where render
uses the previous parameters until a new request is generated
Upvotes: 2