【发布时间】:2013-03-06 19:43:13
【问题描述】:
我开始使用 Ruby on Rails,但遇到了 has_many :through 关联问题。
我正在使用的模型是:
class Phrase < ActiveRecord::Base
attr_accessible :event_type_id, :template_pieces
belongs_to :event_type
has_many :phrases_pieces
has_many :template_pieces, :through => :phrases_pieces
end
class TemplatePiece < ActiveRecord::Base
attr_accessible :datatype, :fixed_text, :name
has_many :phrase_pieces
has_many :phrases, :through => :phrases_pieces
end
class EventType < ActiveRecord::Base
attr_accessible :name
has_many :phrases
end
class PhrasesPiece < ActiveRecord::Base
attr_accessible :order, :phrase_id, :template_piece_id
belongs_to :phrase
belongs_to :template_piece
end
我正在尝试创建一个新短语,将其默认形式编辑为:
<%= form_for(@phrase) do |f| %>
<% if @phrase.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@phrase.errors.count, "error") %> prohibited this phrase from being saved:</h2>
<ul>
<% @phrase.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
Select the event type:
<%= collection_select(:phrase, :event_type_id, EventType.all, :id, :name) %>
Select the phrases to be used:
<%= collection_select(:phrase, :template_pieces, TemplatePiece.all, :id, :name) %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
我首先遇到了批量分配问题,但我修复了将 attr_accessible :template_pieces 添加到短语模型的问题。我不确定这是否是修复它的正确方法,但至少它不再抱怨它无法批量分配受保护的属性。
现在,我在提交新短语时收到以下错误:
“1”的未定义方法`each':String
我认为这是因为一个给定的短语应该有很多模板片段,但我目前一次只能提交一个。所以它只是找到一个,尝试遍历它并失败。
我将如何解决这个问题?有没有更好的方法将带有has_many :through 的模型输入数据库?我是否必须手动执行(如关闭默认控制器 @phrase = Phrase.new(params[:phrase])?
谢谢!
【问题讨论】:
-
有一个完整的堆栈跟踪以及错误会很有帮助。
-
这里显示的错误页面:page capture
标签: ruby-on-rails has-many-through mass-assignment