【问题标题】:Rails: Adding to model after user submits formRails:在用户提交表单后添加到模型
【发布时间】:2012-10-13 00:05:59
【问题描述】:

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

然后是posts_controller.rb中的create函数

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 个是标题的前 2 个字母,后 6 个是随机的小写字母。我该怎么做?

【问题讨论】:

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


    【解决方案1】:
    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
    

    把它放在你的控制器中。您显然必须拥有 random_hash 属性才能使 Post 模型工作。

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

    【讨论】:

    • 第三行应该是params[:title]还是@post.title
    • 在这种情况下,两者都可以正常工作。 params[:title] 将包含与@post.title 相同的标题。随意选择其中之一。
    • params[:post][:title] 不应该和@post.title 一样吗? (我是 Rails 新手,所以如果这是基本的事情,我很抱歉。)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-15
    • 2016-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多