简体   繁体   中英

ruby on rails : adding child records to an existing parent without visiting the parent

How would you handle allowing users to add child objects to parents without requiring them to navigate to the parent?

For example adding a journal article without having to navigate to the journal and issue first? The parent also may not exist yet.

I'd prefer not to make data entry to onerous for users so making them find a journal or create it and then find or create an issue seems a bit much. I would rather just have a single form with journal and issue fields. The logic would simple if were not for the fact that users are interested in the article and not the journal or issue.

Would you just modify a create for the child so it finds or creates the parents ?

I'm assuming you have a journal model that has many articles and an article model that belongs to a journal. First, you should create routes to the articles controller that go through journals and not through journals:

ActionController::Routing::Routes.draw do |map|
  map.resources :journals, :has_many => :articles
  map.resources :articles
end

Now you can get to the new action of your articles controller with the URL /articles/new or /journals/1/articles/new . Then in the new action in your articles controller, you do this:

@article = Article.new(:journal_id => params[:journal_id])

Which set the journal_id of the article to whatever parameter is passed in. If no parameter is passed, the journal_id will be nil.

In the ERB template, you just do this to create the drop down:

<%= f.collection_select :journal_id, Journal.all(:order => "name"), :id, :name, :include_blank => true %>

And then a user can select a journal, but if one was passed in, it will be pre-selected to the correct value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM