2013-09-27 64 views
0

在我的Rails應用程序中,用戶可以創建提交,並且每個提交都有一個標題和內容。現在,在我的提交控制器的創建操作中,它將檢查數據庫中是否存在與提交的新提交的標題相匹配的提交內容。如果數據庫中有一個具有相同標題的數據庫,它將更新已在數據庫中的數據庫,而不是創建另一個數據庫。如果標題爲空(空),創建模型實例?

但是,如果title屬性的值爲NULL(即他們沒有輸入任何內容),我想繼續這樣做,我希望它繼續並創建一個新的實例REGARDLESS如果db中有另一個實例:title值爲NULL。

這裏是我的嘗試,這是不行的:

def create 

    ajax_title = params[:title] 
    ajax_content = params[:content] 
    ajax_folder = params[:folder_id] 
    ajax_parent = params[:parent_id] 
    ajax_children = Array(params[:children]) 

    @submissions = Submission.where(title: ajax_title) 

    if @submissions.empty? 
    @submission = Submission.create({title: ajax_title, content: ajax_content, user_id: current_user.id, folder_id: ajax_folder, parent_id: ajax_parent, children: ajax_children}) 
    else 
    if @submissions.blank? 
     @submission = Submission.create({title: ajax_title, content: ajax_content, user_id: current_user.id, folder_id: ajax_folder, parent_id: ajax_parent, children: ajax_children}) 
    else 
     @submissions[0].content = ajax_content 
     @submissions[0].save 
    end 
    end 
end 

如何檢查並確保與該提交實例:NULL的標題值分別創建和更新不及時另一前一個標題相同值?

回答

1

這應做到:

ajax_title = params[:title] 
ajax_content = params[:content] 
ajax_folder = params[:folder_id] 
ajax_parent = params[:parent_id] 
ajax_children = Array(params[:children]) 

@submission = Submission.find_by_title(ajax_title) 

if ajax_title && @submission 
    @submission.content = ajax_content 
    @submission.save 
else 
    @submission = Submission.create(
     :title=>ajax_title, 
     :content=>ajax_content, 
     :user_id=>current_user.id, 
     :folder_id=>ajax_folder, 
     :parent_id=>ajax_parent, 
     :children=>ajax_children, 
    ) 
end 
+0

這奏效了! –