neonamo neonamo - 20 days ago 5
Ruby Question

How to create an object from array by calling back create action? Ruby on rails

I am stuck at: I need to create a text and the same way I need to create a list of words out of the created text. So what I did:

I created create action in my text controller:

def create
@text = Text.new(text_params)

if @text.save
redirect_to text_path(@text), notice: "Text successfully created"
else
render :new
end
end


Here is the form for creating a text:

<%= form_for @text do |f| %>
<div class="form-group">
<label>Text name</label>
<%= f.text_field :name %>
</div>

<div class="form-group">
<label>Description</label>
<%= f.text_area :description%>
</div>

<div class="actions">
<%= f.submit "Save", class: "btn btn-primary" %>
</div>

<%end%>


In the Text Model I created after_create callback:

class Text < ApplicationRecord
has_many :words
after_create :create_words

def create_words

@word = Word.new( word_params )

@text.split(/\W+/)
@text.each do |splitted|
if splitted != @words.name
splitted = @word
@word.save
redirect_to root_path
else
render :new
end
end
end


def word_params
params.require(:word).permit(:name, :translation)
end

end


I am new to RoR and Please help me out to fix my issue. Basicly what I need is when I am creating text for instance a text is:


I have a dog


should be placed on my
texts
table and each word:


I, have, a, dog


should be placed in my
words
table in the database.

Thank you very much in advance.

Answer

redirect_to is a routes helper that are available in controllers. So, you should just work on model object on your model class. update your create_words method with the following content.

class Text < ApplicationRecord
  has_many :words
  after_create :create_words


  private
    def create_words
      # self is the Text object in context 
      # i.e the Text object on which after_create is called
      words = self.description.split(/\W+/)
      words.each do |splitted|
        self.words.create(name: splitted, translation: '')
      end
    end

end

So every time you save save a Text object, after_create :create_words is triggered, which splits the Text object in context (self) and each word is iterated to create a new associated Word object on your words table.