Putting create action for one model in show page of another
I asked this question earlier and got part of the way to where I needed to be.
I have a simple app that has开发者_C百科 three tables. Users, Robots, and Recipients. Robots belong_to users and Recipients belong_to robots.
On the robot show page, I want to be able to create recipients for that robot right within the robot show page.
I have the following code in the robot show page which lists current recipients:
<table>
<% @robot.recipients.each do |recipient| %>
<tr>
<td><b><%=h recipient.chat_screen_name %></b> via <%=h recipient.protocol_name</td>
<td><%= link_to 'Edit', edit_recipient_path(recipient) %> </td>
<td><%= link_to 'Delete', recipient, :confirm => 'Are you sure?', :method => :delete %></td>
</tr>
<% end %>
</table>
and now I have this in the Robot show view:
<% form_for(@recipient) do |f| %>
Enter the screen name<br>
<%= f.text_field :chat_screen_name %>
<p>
<%= f.submit 'Update' %>
</p>
<% end %>
and the robots controller has this added to it also:
@recipient = Recipient.new
@recipients = Recipient.all
I now see the field I want to see, but it seems as though the recipient is still not being associated with the robot who's show page the user is on. Moreover, when I have this code in, the redirect upon creation is going to the recipients index page, as opposed to the robot show page.
I have this code in the recipents controller in the create action:
def create
@recipient = Recipient.new(params[:recipient])
respond_to do |format|
if @recipient.save
flash[:notice] = 'The new recipient was successfully added.'
format.html { redirect_to (robot_path(@recipient.robot)) }
format.xml { render :xml => @recipient, :status => :created, :location => @recipient }
else
format.html { render :action => "new" }
format.xml { render :xml => @recipient.errors, :status => :unprocessable_entity }
end
end
end
I'd really appreciate any additional help. I know I'm close to the solution but not quite there.... :)
Thanks.
@recipient = Recipient.new(params[:recipient])
This creates a new Recipient based on the submitted form, but there's nothing in the form designating the robot you want to use. Because there's no params[:recipient][:robot_id], there can't be a @recipient.robot.
Either try a nested resource and accessing the robot id from the url params, or try passing a hidden field containing the robot id and accessing it from the submitted form.
Key point here: params[:recipient] only contains what's passed from the form, and you aren't passing the robot id anywhere.
Use a nested route and then in create: (this is a slightly different approach that the other answer)
@robot = Robot.find(params[:bug_id])
@recipient = Robot.recipients.new(params[:recipient])
This will automatically create @recipient
with robot_id
set correctly.
精彩评论