Rails ActiveRecord不会在创建时保存关联,但会在更新时保存

时间:2013-12-31 21:16:17

标签: ruby-on-rails activerecord

我的控制器中有以下创建和更新方法:

  def new
    if request.post?
      @article = Article.new(article_params)
      @article.user = @user
      if @article.save
        redirect_to :admin_articles, :flash => { success: t(:article_created) }
      end
    else
      @article = Article.new
    end
  end

  def edit
    if request.patch?
      if @article.update(article_params)
        redirect_to :admin_articles, :flash => { success: t(:article_updated) }
      end
    end
  end

我对article_params有以下内容:

    def article_params
        article_params = params[:article].permit(:category_id, :title, :slug, :article_type, :content, :link, :summary)
        if params[:tags].present?
          tags = params[:tags].split ','
          tags_array = Array.new
          tags.each do |t|
            tags_array.append Tag.find_or_create_by slug: t
          end

          article_params[:tags] = tags_array
        end

    article_params
  end

当我执行更新时,它会正确保存,但是当我尝试创建它时,文章标签无效。有谁知道我做错了什么?

2 个答案:

答案 0 :(得分:1)

你的控制器中没有(或至少没有显示)create方法,所以你只是获得了ActiveModel的默认实现,它不会获取任何参数。如果您对路线做了非标准的事情,那么POST会映射到new,请分享。

答案 1 :(得分:0)

问题是我不理解惯例。我的对象尚未创建,因此它还没有标签属性。我已将方法更改为以下内容:

    def article_params
        params[:article].permit(:category_id, :title, :slug, :article_type, :content, :link, :summary)
      end

      def tags
        tags = Array.new

        if params[:tags].present?
          tag_param_array = params[:tags].split ','
          tag_param_array.each do |t|
            tags.append Tag.find_or_create_by slug: t
          end
        end

        tags
      end

      def new
    @article = Article.new
  end

  def create
    @article = Article.create article_params
    if @article.valid?
      @article.tags = tags

      redirect_to :admin_articles, :flash => { :success => t(:article_created) } if @article.save
    else
      render 'new'
    end
  end

  def edit
  end

  def patch
    @article.update_attributes article_params
    if @article.valid?
      @article.tags = tags

      redirect_to :admin_articles, :flash => { :success => t(:article_updated) } if @article.save
    end
  end