更新记录,如果存在,则创建新的记录栏

时间:2013-09-22 12:26:25

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

这是我的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

以上代码只是每次创建新记录

1 个答案:

答案 0 :(得分:3)

gen_id是Post表单的一部分。但是你在顶级寻找它。你需要这样做:

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

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