views:

1436

answers:

4

New to rails and trying to get a one to many relationship up and running. I have it working in the Model and Controller, but I'm having trouble getting it up and running in the views.

class Project < ActiveRecord::Base
  has_many :non_labor_expenses
end

class NonLaborExpense < ActiveRecord::Base
  belongs_to :project
end

I manually created some entries in the the non_labor_expense table by loading the @non_labor_expenses in the controller (edit action) and can pull the existing data in the project view like so:

<% unless @non_labor_expenses.nil? %>
  <% count = 1 %>
  <% for expense in @non_labor_expenses %>
    <li>
      <div class="label"><%= f.label :expense , "Expense" + count.to_s %></div>
      <%= '$' + expense.amount.to_s + ' - ' + expense.description.to_s %>

    </li>
  <% count = count +1 %>
  <% end %>

<% end %>

What I am having trouble doing is adding a new non_labor_expense entry to the project. I should be able to manage handling it on the backend, but I can't even get the field to show up in the form.

Here's where I'm at now:

<li class="editable">
  <div class="label"><%= f.label :non_labor_expenses %></div>
  <%= f.text_field :non_labor_expenses %>
</li>

I know my above code looks nothing like this, but ideally the form fields would be something like:

Expense Amount [text input]
Expense Description [text input]

My full form code can be found here: http://pastebin.com/m2b280b0f

A: 

non_labor_expenses is not a text field, which is probably your biggest problem.

A better way to do this might be to create a new non_labor_expense, and in its creation have a dropdown select box to pick the id (or name, through the id) of the project.

Justin
I realize it's not a text field, but I have no idea what to use.I agree, but the site is designed in such a way that the non-labor expenses need to be able to be added on the project edit page.
easement
+2  A: 

Assuming you can only add one per form (versus JS to add [n] new non labor expenses), just create an empty instance variable in the controller.

@new_non_labor_expense = NonLaborExpense.new

In the form, build it out using:

<%= f.text_field :new_non_labor_expense, :amount %>

Or whatever the appropriate member var and field type are.

In the controller, you'll get a param called "new_non_labor_expense" and can access it, validate it, associate it, and save it. Or, if any of those steps err you can bounce back and notify the user.

If you need to add more, just make an array of them so you pass in an array of NLEs. Hope that makes sense.

Toby Joe Boudreaux
A: 

I think what you need are nested forms. Here is simple example how to do it with one to many relation. It works since Rails 2.3.2

klew
+1  A: 

Another option would be fields_for - which seems to work just fine for me. Check out Railscasts 73 - 75.

Andy Gaskell