views:

19

answers:

2

Hi, I'm a Rails newbie and want to do something but keep messing something up. I'd love some help.

I have a simple app that has 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) %>&nbsp;</td>
    <td><%= link_to 'Delete', recipient, :confirm => 'Are you sure?', :method => :delete %></td>
  </tr>
<% end %>
</table>

What I'd like to do is have an empty field in which the user can add a new recipient, and have tried the following:

I added this to the Robots Show view:

<% form_for(@robot.recipient) do |f| %>
Enter the screen name<br>
<%= f.text_field :chat_screen_name %>
<p>
  <%= f.submit 'Update' %>
</p>
<% end %>

and then this to the Robot controller in the show action:

@recipient = Recipient.new
  @recipients = Recipient.all

Alas, I'm still getting a NoMethod error that says: "undefined method `recipient' for #"

I'm not sure what I'm missing. Any help would be greatly appreciated.

Thank you.

A: 

Rather than calling @robot.recipient in the form, you probably want @recipient.

ealdent
This worked in that I can see the field on the robot show page, but it appears it's not attaching the recipient to the particular robot. I have this in the recipient controller for the create action: @recipient = Recipient.new(params[:recipient]) and later: format.html { redirect_to (robot_path(@recipient.robot)) }When I put something in and create it, it goes to the recipients index page, and gives me an error of: undefined method `Recipient' for #<Class:0x1040aa618>Doesn't seem to be routing to the robot show page as I'd expect, nor saving the recipient as belonging to the robot.
Andrew
@ealdent sorry, ran out of space, but wanted to say thanks for the help so far. Any thoughts on what might be happening?
Andrew
A: 

Use @recipient, like @ealdent says.

Your update action should be somewhat similar to this:

def update
  @robot = Robot.find(params[:id])
  @robot.recipients.build(params[:recipient])
  ...
end

This will create the recipient in the collection for the given robot.

But there are much better ways to do this, where you can add an unlimited number of recipients, as explained here

Hope this gets you started.

nathanvda
This is causing a No Method error when I hit create. It says: undefined method `recipients' for nil:NilClass.So I'm being clear, this is what I have in the recipients controller in the create action: @recipient = @robots.recipients.build(params[:recipient])
Andrew
I clarified a bit i hope. It should be @robot, not @robots.
nathanvda