Paul S.
Paul S.

Reputation: 4492

Rails: Adding to model after user submits form

In my Rails 3.2 project, I have a form to create a new post in new.html.erb in app/views/posts/

<%= form_for(@post) do |post_form| %>
  ...
  <div class="field">
    <%= post_form.label :title %><br />
    <%= post_form.text_field :title %>
  </div>
  <div class="field">
    <%= post_form.label :content %><br />
    <%= post_form.text_field :content %>
  </div>
  <div class="actions">
    <%= post_form.submit %>
  </div>
<% end %>

Then the create function in posts_controller.rb

def create
  @post = Post.new(params[:post])  
  if @post.save
    format.html { redirect_to @post }
  else
    format.html { render action: "new" }
  end
end

When the user submits a post, the title and content of the post are added to the Post model. However, I also want to add to another field of that post. For the field random_hash (which the user doesn't get to specify), I want to make it a string of 8 lowercase letters, the first 2 of which are the first 2 letters of the title, and the last 6 are random lowercase letters. How can I do that?

Upvotes: 2

Views: 125

Answers (1)

Jason Kim
Jason Kim

Reputation: 19051

def create
  @post = Post.new(params[:post])
  @post.random_hash = generate_random_hash(params[:post][:title])
  if @post.save
    format.html { redirect_to @post }
  else
    format.html { render action: "new" }
  end
end

def generate_random_hash(title)
  first_two_letters = title[0..1]
  next_six_letters = (0...6).map{65.+(rand(25)).chr}.join
  (first_two_letters + next_six_letters).downcase
end

Put that in your controller. You obviously have to have random_hash attribute for Post model to work.

I am using Kent Fredric's solution to generate six random letters.

Upvotes: 4

Related Questions