【问题标题】:How do I get form_for(@example) to work inside my Collections#show when example belongs_to Collection如何让 form_for(@example) 在我的 Collections 中工作#show when example belongs_to Collection
【发布时间】:2013-08-20 17:07:45
【问题描述】:

这似乎是我(可能在概念上)再次出现的问题,希望这次我能解决它! #stillLearning

两种型号。 一个集合 has_many :examples 一个例子 belongs_to :collection

集合有一个标题:字符串 示例有collection_id:整数和描述:文本

在我的收藏/展示中,我还希望能够通过这个简单的表单添加一个示例:

<%= form_for(@example) do |e| %>

    <h3><%= e.label :description %></h3>
    <%= e.text_area :description %>
    <%= e.submit %>

<% end %>

但是我得到一个 NoMethodError...

undefined method `description' for #<Collection:0x007fe3c4087898>. 

我知道@collection 没有 :description,所以这意味着我必须在 Collection 和 Example 之间创建一个链接,对吗?

假设我的猜测是正确的,我尝试了:

rails g migration AddExampleRefToCollections example:references

但出现以下错误:

SQLite3::SQLException: near "references": syntax error: ALTER TABLE "collections" ADD "example" references/Users/davidngo/.rvm/gems/ruby-1.9.3-p429/gems/sqlite3-1.3.8/lib/sqlite3/database.rb:91:in `initialize'

【问题讨论】:

标签: ruby-on-rails rails-migrations rails-models


【解决方案1】:

如果Collection 有很多Examples,那么Example 应该是数据库中通过id 引用Collection 的那个:

rails g migration AddCollectionIdToExamples collection_id:integer

在 CollectionsController#show 中,确保您正在实例化一个新的空示例以在您将要使用的 form 中使用:

def show
  #stuff
  @example = @collection.examples.new

【讨论】:

  • 谢谢@PabloB。这允许我的表单显示在 CollectionsController#show 中。但是现在,当我单击“创建”示例时,它在 ExamplesController#create 方法中找不到集合 ID。当 collection_id 不是参数的自动一部分时,如何将它链接到示例?
  • 上面的错误已经被这个线程解决了:stackoverflow.com/questions/16138353/… 本质上,路由必须嵌套,这样collection_id 是参数的一部分。我现在更好地理解路由了!是的!进步的感觉!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-21
  • 1970-01-01
  • 2012-03-25
  • 1970-01-01
  • 2013-06-21
  • 1970-01-01
相关资源
最近更新 更多