neonamo neonamo - 21 days ago 6
Ruby Question

How to do two actions in one action of the controller

I need to create some text. I have a create action:

def create
@text = Text.new(text_params)

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


and the form:

<%= 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%>


I need to have two action when I am submitting my text. The first action is going to create a text. The second is to create words out of the text words and should make a list of words.

When creating a word I need to have an
if
statement create a word if not present.




I am now having an issue with how I can split and create each word:

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

Answer

The simplest way would be to do your words thing in an after_create callback.

class Text < ApplicationRecord
  after_create :create_words


  private

  def create_words
    # do your thing here
  end
end

create_words will be called when a Text is successfully created.