Hi,
> <%= collection_select(:person, :organization_id,
> @@organizations, :id, :name) %>
Even if this would work, I'd strongly advise against
it since the view has more knowledge of your controller
than it needs to and turns your nice MVC app into
a tangled mess. Just use a normal instance variable
here (@organizations). That gives the controller a chance
to manipulate the organizations list (e.g. certain users
may only create people for a subset of all available
organizations, etc.) without requiring changes in the view.
Regarding the controller: Isn't it possible that the
list of organizations changes? Your current code doesn't
account for that. In this case the right way is a simple
def new
@organizations = Organization.find(:all)
...
def edit
@organizations = Organization.find(:all)
...
If the organizations don't change, and you _really_
want to load the only once, just add
def new
@organizations = @@organizations
...
HTH,
Stefan
It's not that this isn't DRY, it's that each call to the method must
allow for the fact that the Organization model changes. The controller
shouldn't assume that it is the only way of accessing a model which is
what you'll do by updating a controller class variable whenever the
controller changes a model. This will lead to problems down the line if
you end up with other accesses to the model. This may not seem
important for this application, but it would be a bad habit to get into
as it will definitely bite you on a larger project.
It is unlikely you are expecting a large number of organisations as that
would make your select list unwieldy. So obtaining the list from the
database should be fairly low cost. Let your database handle data
caching and let your application handle access control and logic. When
doing a find(:all) the database will do a bulk load in one call which
shouldn't be much more expensive than getting a single row for small
amounts of data (and so comparable to the cost of adding the new People
record) and if you are using a decent database, it may have cached the
results for you anyway. Also, at this stage, you don't know how
noticable caching this value yourself will be. Use profiling to decide
where to target performance efforts.
When starting out, it's probably more useful to concentrate on
functionality rather than minor details and look at how you can refactor
later once the application takes shape. As you play with more
applications and look at other's code, you'll start recognising
opportunities for factoring earlier in development.
Finally, if you really want to cache the records, put them where they
belong. In the model. All access must go through the model, so use the
model's after_* hooks to keep a cache in the model and provide access to
this cache (which will even be available from a view if you really need
it there).
--
Posted via http://www.ruby-forum.com/.