2012-10-13 34 views
2

在我的Rails 3.2的項目,我有一個表格在app/views/posts/的Rails:添加到用戶後模型提交形式

<%= 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功能創建new.html.erb一個新的職位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個是標題的前2個字母,最後6個是隨機小寫字母。我怎樣才能做到這一點?

回答

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.

+0

它應該是'PARAMS [:標題]'或在第三行'@ post.title'呢? –

+0

在這種情況下應該工作正常。 'params [:title]'將包含與@ post.title相同的標題。隨意選擇其中之一。 –

+0

不應該'params [:post] [:title]'與'@ post.title'相同嗎? (我是Rails的新手,所以我很抱歉,如果這是一個基本的東西。) –

相關問題