Rails:在用户提交表单后添加到模型

时间:2012-10-13 00:05:59

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.2

在我的Rails 3.2项目中,我有一个表单可以在new.html.erb中的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 %>

然后create

中的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

当用户提交帖子时,帖子的titlecontent会添加到Post模型中。但是,我还想添加到该帖子的另一个字段。对于字段random_hash(用户没有指定),我想让它成为8个小写字母的字符串,前两个字母是标题的前2个字母,最后6个字母是随机小写字母。我怎么能这样做?

1 个答案:

答案 0 :(得分:4)

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

将它放在你的控制器中。显然,Post模型必须具有random_hash属性才能工作。

我正在使用Kent Fredric's solution to generate six random letters.

相关问题