0

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.

Mario
  • 1,213
  • 2
  • 12
  • 37
  • Hi marcpt, the information you provide is not enough. What did you try so far? You share javascript code, but it's not very relevant, this is how you **send** data to the server, what you are asking for is how to save it. – roman-roman Sep 14 '14 at 10:01
  • Have you created the article model with the title and attributes and set up a controller and routes? If so, please show us the code. – Martin Poulsen Sep 14 '14 at 11:27
  • But there is another way to store a json object? I only know this way (but I don't know how to make it work). I have posted the controller that I'm using. Once I understand how is it done I will use it with a more complex json object that I generate in a JS diagram tool. But for know I'm just trying with this simple example. I have searched but I always found forms and I don't have a form I just have a json object and I want to store it. If you also can point me to some tutorial with this, I really appreciate. This must be simple but I'm new at developing in ruby on rails. – Mario Sep 14 '14 at 18:33

1 Answers1

1

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
Christian Rolle
  • 1,664
  • 12
  • 13