2013-09-22 48 views
-1

這是我new.html.erb更新記錄,如果存在其他創造新紀錄的軌道

<%= form_for @post do |f| %> 
    <%= f.text_field :title,placeholder: 'title' %> 
    <%= f.hidden_field :gen_id,value: 55 %> #55 is just for testing 
    <%= f.submit 'Submit' %> 
<% end %> 

這是我的控制器

def create 
     @post = Post.find_by_id params[:gen_id] 
     if @post 
     @post.update(post_params) 
     else 
      @post = Post.new 
      if @post.save! 
       flash[:success] = 'Post added successfully' 
       redirect_to action: :new 
      else 
       flash[:error] = 'Post cannot add. Please try again after some time' 
       redirect_to action: :new 
      end 
     end 
    end 

上面的代碼只是創造新的記錄,每次

+0

你在軌道3使用強PARAMS? – Santhosh

+0

@acts_as_geek我正在使用rails 4 – overflow

+1

有一個'find_or_create_by(...)'方法 – j03w

回答

3

gen_id是郵政形式的一部分。但是你正在尋找它的頂級水平。你需要這樣做:

@post = Post.find_by_id params[:post][:gen_id] 

@post = Post.where(id: params[:post][:gen_id]).first 
+0

是的,我改變了它。它進入這個循環'if @ post',但我無法在我的表中找到任何更新。我也嘗試過'update_attributes'。還有其他的變化嗎? – overflow

相關問題