【问题标题】:Combine multiple models in a Rails form to create a new object在 Rails 表单中组合多个模型以创建新对象
【发布时间】:2012-02-11 00:01:47
【问题描述】:

我有两个模型,Story 和 Category。使用Story#new 的表单,我希望能够保存类别的外键。

要在我使用过的Story#new 表单页面上显示类别中的选择数据:

<%= collection_select(:category , :category, Category.all , :id, :category, {:prompt => 'Select Category...'}) %>

如何将category_id 保存到新创建的 Story 对象中?


故事有属性:industry_iduser_id,类别有属性name development.log 告诉我:(看起来它正在尝试将新类别 (99) 添加到类别表中

Started POST "/stories" for 127.0.0.1 at 2012-02-10 17:32:56 -0600
 Processing by StoriesController#create as HTML
story"=>{"industry_id"=>"8", "user_id"=>"8"}, "category"=>{"category"=>"99"}, "commit"=>"Create Story"}

【问题讨论】:

  • Story belongs_to 分类吗?协会是如何布局的?
  • 是的:class Story < ActiveRecord::Base has_many :industries has_many :categoriesclass Category < ActiveRecord::Base belongs_to :story
  • 所以其实故事有_许多类别

标签: ruby-on-rails forms


【解决方案1】:

我认为您需要将参数更改为collection_select。第一个参数是模型的名称。第二个参数是将值分配给的模型属性的名称。第四个参数是Category对象的方法,用作选择选项的文本值。

我相信它应该是这样的:

<%= collection_select(:story , :category_id, Category.all , :id, :name, {:prompt => 'Select Category...'}) %>

您可能还想查看ActiveRecord nested attributes

【讨论】:

  • 那是准确的答案,谢谢 Brandan!我仍然将它保存到 Category 模型,因为第一个参数是 :category
猜你喜欢
  • 2016-01-22
  • 2014-11-12
  • 1970-01-01
  • 1970-01-01
  • 2017-05-07
  • 2014-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多