Reputation: 5086
I'm pretty much a Rails beginner, at the moment developing a rather complex webapp in Rails 2.2.
So, in this webapp, there are "factories". Not the design pattern, mind you, actual factories (it's a game).
For each factory in a player's team, there are a bunch of options he can take.
I have two problems with this:
Can anyone help me with this? This is all way over my head.
Thanks all.
Upvotes: 0
Views: 215
Reputation: 335
To understand question 1, keep it simple and pretend the attributes you want to access are in the factories table. The design pattern then is pretty simple:
Database schema:
create_table :factories do |t|
t.boolean :now_operating, :default => true, :null => false
...
Controller:
def edit
@factory = Factory.find(params[:id])
if request.post?
@factory.update_attributes(params[:factory])
end
end
View:
<% form_for :factory, @factory, :url => { :action => "edit" } do |f| %>
<%= f.checkbox :now_operating %>
...
You can do this with less code, in fact with none at all if you use RESTful resources and follow naming conventions, but this is a little too much magic to start off, because it conceals what rails is doing for you.
Namely: when the :get action loads an object matching the object name passed to form_for, rails will populate the form fields with that object's attribute values from the database. Then, when the client submits the form, rails encodes those fields into the request as params for that object, which you can then update in the :post action. See the official Rails Guide for a more detailed treatment.
I apologize if that was a little too basic, but it's important to get the basic pattern because the general approach to solving problem 2 is the same:
There are several ways of actually doing this for forms with multiple objects. I suggest you see the various tutorials listed under Item 8, Building Complex Forms, in the Rails Guide.
Two last points to consider:
Upvotes: 1
Reputation: 29877
if the child entities (level of maintenance, performace, etc) are linked to the Factory, then you can use nested model forms.
You can check some info about nested forms here, or just google "rails nested forms" and you'll get plenty of blog posts and tutorials.
--EDIT Seeing that you added that you're using rails 2.2, you could try to use simple_forms or formtastic to create the nested forms (this is just a suggestion as I have no idea if it works). And I can only thing of setting the values manually to update the models.
Upvotes: 1