使用accepts_nested_attributes_for时如何编辑连接模型的属性?
我有3个模型:由连接器加入的主题和文章
class Topic < ActiveRecord::Base
has_many :linkers
has_many :articles, :through => :linkers, :foreign_key => :article_id
accepts_nested_attributes_for :articles
end
class Article < ActiveRecord::Base
has_many :linkers
has_many :topics, :through => :linkers, :foreign_key => :topic_id
end
class Linker < ActiveRecord::Base
#this is the join model, has extra attributes like "relevance"
belongs_to :topic
belongs_to :article
end
Run Code Online (Sandbox Code Playgroud)
所以当我在主题控制器的"新"动作中构建文章时......
@topic.articles.build
Run Code Online (Sandbox Code Playgroud)
...并在topics/new.html.erb中创建嵌套表单...
<% form_for(@topic) do |topic_form| %>
...fields...
<% topic_form.fields_for :articles do |article_form| %>
...fields...
Run Code Online (Sandbox Code Playgroud)
... Rails自动创建链接器,这很棒. 现在我的问题是:我的链接器模型还具有我希望能够通过"新主题"表单更改的属性.但是Rails自动创建的链接器除了topic_id和article_id之外,其所有属性都有nil值.如何将其他链接器属性的字段放入"新主题"表单中,这样它们就不会出现?
不应该Rails find_by_方法返回一个空数组而不是nil?
没有与find_by_条件匹配的记录是正常的,但返回nil没有意义.因为在我看来,错误是由合理的代码引起的,例如:
<% for thing in @thing_that_might_be_an_array_or_might_be_nil do %>
Run Code Online (Sandbox Code Playgroud)
由于find_by_总是返回一个数组,即使只有1条记录,如果有0条记录,它也应该返回一个数组.然后是所有这些
<% @thing.each
Run Code Online (Sandbox Code Playgroud)
和
<% for thing in @thing
Run Code Online (Sandbox Code Playgroud)
在我们的观点中,我们会悄悄地过去,而不是造成"我们很抱歉,但出了点问题." (或者我错过了什么?目前解决这个问题的最佳做法是什么?)