我开始使用Ruby on Rails,并且遇到关联has_many :through
的问题。Rails协会has_many:通过
我使用的型号有:
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’:现在
,提交一个新词时,我收到以下错误字符串
哪我还挺想偏偏因事实上,对于给定的短语应该有很多template_pieces,但是我目前只能一次提交一个。所以它只是找到它,试图遍历它并失败。
我该如何解决这个问题?将数据库has_many :through
输入模型有没有更好的方法?我是否必须手动执行此操作(如解除默认控制器@phrase = Phrase.new(params[:phrase]
)?
谢谢!
有一个完整的堆栈跟踪以及错误会很有帮助。 – adamdunson 2013-03-06 20:02:18
以下是显示的错误页面: [page capture](https://www.dropbox.com/s/62dat91bx4dh2jg/error_msg.png?m) – snowingheart 2013-03-06 23:49:16