简体   繁体   English

Ruby on Rails:将子记录添加到现有父项中,而无需访问父项

[英]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 . 现在,您可以使用URL /articles/new/journals/1/articles/new进入Articles控制器的新操作。 Then in the new action in your articles controller, you do this: 然后在您的Articles控制器中的新操作中,执行以下操作:

@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. 哪个将文章的journal_id设置为传递的任何参数。如果未传递任何参数,则journal_id将为nil。

In the ERB template, you just do this to create the drop down: 在ERB模板中,只需执行以下操作即可创建下拉列表:

<%= 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. 然后,用户可以选择日记帐,但是如果日记帐被传递,它将被预先选择为正确的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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