Initially I created Exercises to browse. Then I added the ability to record “log_entries” against them.
This works for that
= semantic_form_for @exercise do |exercise|
= exercise.semantic_fields_for :log_entries do |log_entry|
= render 'log_entries/log_entry_fields', :f => log_entry
.links
= link_to_add_association 'Add Set', exercise, :log_entries, :partial => "log_entries/log_entry_fields", :data => {:role => "button", :icon => "plus"}
= exercise.buttons do
= exercise.commit_button "Apply", :button_html => {:data => {:icon => "check", :theme => "b"}}
= link_to "Cancel", "", :data => {:rel => "back", :icon => "delete", :role => "button", :theme => "a"}
I now added the requirement of needing it to be associated to a user. I’m not sure how to do that in the best manner. This is posting to the exercise controller now, and an exercise isn’t really associated with a user. So in the exercise controller I could merge the params in, but that seems hackish.
The proper way would be to create the log entry association through the user, right? But how would I restructure the form to make that work?
I probably shouldn’t be using the exercise controller anymore either for that since it’s creating log_entries, and then in the LogEntryController the user can be set through there… but what’s the best way to do this? For some reason I can’t figure out how to pass in the workout to the log_entries controller and then have the collection render in the form like shown.
Maybe I’m brain pooped from coding all day. Thanks!
I’m using the Cocoon library for the add association functionality.
You don’t need a gem to accomplish this. Consider the following associations:
And the following deeply-nested routes:
Which would result in a new link looking like this (long, I know):
where
userandexerciseare the user and exercise objects that thelog_entrywill belong to. The resource part of your URI would look something like this, for example:Note, that it’s the log_entry form that you should be submitting, not the exercise form.
And you wouldn’t have to do anything special with your log_entry form. Since the relations exist between the models and the routes are nested, you can simply access the
params[:user_id]andparams[:exercise_id]in yourlog_entrycontroller action and assign them to your newlog_entryobject there.