Mario
Mario

Reputation: 1253

Store json object in ruby on rails app

I have a Json object that I have to store in a ruby on rails application.

How can I store a json object in a ruby on rails application?

Witch is the best way to do it?

I have tried with a jquery ajax request like this:

$.ajax({
    url: "/articles",
    type: "POST",
    data: { "article": { "title": "firsttitle", "text": "text of the article" } }
  });

but without success.

Edit:

Article controller:

def create
        render plain: params[:article].inspect
        #@article = Article.new(article_params)

        #@article = Article.create(article_params)
        #if @article.save
        #   redirect_to @article    
        #else
        #   render 'new'
        #end
    end

Edit:

It is working!

The ajax call:

  $.ajax({
    url: "/articles",
    type: "POST",
    data: datatosend,
    dataType: "json",
    success: dataSaved()
  });

  function dataSaved(){
    alert("Success on send data to server.");
    location.reload();
  }

And this controller:

def create
    @article = Article.new(article_params)

    if @article.save
        redirect_to @article    
    else
        render 'new'
    end
end

but the redirects didn't work. Can anyone explain me why the redirects didn't work? I didn't fully understand the mechanism of this ajax jquery calls to the controllers methods.

Upvotes: 0

Views: 1050

Answers (1)

Christian Rolle
Christian Rolle

Reputation: 1694

Just to answer your question:

How can I store a json object in a ruby on rails application?

Add an attribute to the model table you wish to store the JSON object and enhance the model like:

class Food < ActiveRecord::Base
  def ingredient= object
    write_attribute :ingredient, object.to_json
  end

  def ingredient
    JSON.parse(read_attribute :ingredient)
  end
end

and:

@food = Food.new ingredient: Ingredient.first
@food.ingredient

Upvotes: 1

Related Questions