How to create a model form that has its own relationship on its own

I have a Phrase class that has_many Phrase as Translation .

application / 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 

application / 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 

And I want to add forms of "translatability" for each "phrase".

application / 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> 

This code has an infinite loop error.

 undefined method `phrase_phrase_phrase_phrase_phrase_phrase_... 

How to create forms for translating source phrases?

application / models / translatability.rb

 class Translatability < ActiveRecord::Base belongs_to :phrase belongs_to :translation, :class_name => 'Phrase' end 
+6
source share
1 answer

I think you can complicate this method a bit. If I understand correctly, you have Phrase , which can be translated into several languages. It seems to me that you really want to have a Phrase model that defines the language and has a link that allows you to link other translations.

Phrase will look something like this:

 create_table :phrases do |t| t.text :body t.string :locale t.integer :translation_ref_id end 

In the Phrase model, you can define translations methods:

 def translations self.class .where(translation_ref_id: translation_ref_id) .where.not(id: id) end 

In your form, you will have several Phrases instead of one Phrase with nested attributes. And in the controller you must set translation_ref_id for each of the Phrase (you can use any unique identifier, incrementing whole identifiers is good, you do not need a separate model for tracking identifiers).

+2
source

All Articles