【发布时间】:2016-03-14 10:44:37
【问题描述】:
我有一个 Phrase 类 has_many Phrase 为 Translation。
app/models/phrase.rb
class Phrase < ActiveRecord::Base
has_many :translatabilities
has_many :translations, through: :translatabilities
has_many :inverse_translatabilities, class_name: "Translatability", foreign_key: "translation_id"
has_many :inverse_translations, through: :inverse_translatabilities, source: :phrase
accepts_nested_attributes_for :translatabilities
end
app/models/phrases_controller.rb
class PhrasesController < ApplicationController
def index
@phrases = Phrase.all.page params[:page]
@translations = @phrases.count.times.map do |i|
translation = Phrase.new
translation.translatabilities.build
translation
end
end
end
我想为每个“短语”添加“可翻译性”表格。
app/views/phrases/index.html.erb
<table>
<tbody>
<% @phrases.each do |phrase| %>
<tr>
<td><%= phrase.text %></td>
</tr>
<tr>
<td>
<%= form_for @translations do |f| %>
<%= f.text_field :text %>
<%= f.submit 'translate' %>
<%= f.fields_for :translatabilities do |t_form| %>
<%= t_form.hidden_field :id %>
<% end %>
<% end %>
</td>
</tr>
<% end %>
</tbody>
</table>
此代码存在无限循环错误。
undefined method `phrase_phrase_phrase_phrase_phrase_phrase_...
如何创建用于翻译原始短语的表单?
app/models/translatability.rb
class Translatability < ActiveRecord::Base
belongs_to :phrase
belongs_to :translation, :class_name => 'Phrase'
end
【问题讨论】:
-
我知道性病。在这种情况下我应该使用 STI 吗?
-
是的。因此,您可以同时拥有原始短语和翻译短语。这样一来,您就可以使用单个表继承来表达。
-
不,短语实例也被视为其他短语的翻译,例如
Friend同时是User,但您不能使用 STI 创建Friend类。我是不是误会了? -
如果您想使用 STI 创建
Friend,您只需从User继承,如class Friend < User; end。您可以对Translation和Phrase执行相同的操作
标签: ruby-on-rails has-many-through