Darren
Darren

Reputation: 11021

Rails ActiveRecord Won't Save Associations On Create But Will On Update

I have the following methods for Create and Update in my Controller:

  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

And I have the following for the 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

When I do the Update it saves properly, but when I try to do the Create it says Article Tags is invalid. Does anyone know what I am doing wrong?

Upvotes: 0

Views: 184

Answers (2)

Darren
Darren

Reputation: 11021

the issue was me not understanding convention. My object had not been created therefore it did not have a tags property yet. I have changed my methods to the following:

    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

Upvotes: 0

Peter Alfvin
Peter Alfvin

Reputation: 29389

You don't have (or at least haven't shown) a create method in your controller, so you're just getting ActiveModel's default implementation which isn't going to pick up any of the params. If you're doing something non-standard with your routes, such that POST is getting mapped to new, please share that.

Upvotes: 1

Related Questions