I
I
isd12272016-03-10 16:56:38
Ruby on Rails
isd1227, 2016-03-10 16:56:38

How to write to json on ruby ​​on rails?

I never got an answer to the question I asked before, so I decided to rephrase it.
I have a form written in RoR, I need to make sure that when I fill in the fields in this form:
Name: "input"
City: "input"
Phone: "input"
The values ​​of "input" should be written to a JSON document in the form :

{
  "data": [{
    "name": "ввод",
    "сity": "ввод",
    "phone": "ввод"
  }, {
    "name": "ввод",
    "сity": "ввод",
    "phone": "ввод"
  }
}

In PHP, it seems to be done something like this:
<?
session_start();
  require_once("include/db_connect.php");
?>

<?
if($_SERVER["REQUEST_METHOD"] == "POST"){
  $id=$_SESSION['id'];
  $name_marker=$_POST['name_marker'];
  $description_marker=$_POST['description_marker'];
  $sh=$_POST['sh'];
  $dg=$_POST['dg'];
  $rt=$_POST['rt'];
  
  if(!empty($_SESSION['login_suc'])){
    $sql="INSERT INTO 
    `markers`(`id_marker`, `id_user`, `title`, `desc`, `reit`, `sh`, `dg`) VALUES
     ('','".$id."','".$name_marker."','".$description_marker."','".$rt."','".$sh."','".$dg."')";
      $stmt=$dbh->prepare($sql);
      $stmt->execute();
      echo "Вы добавили маркер";
    $sql="SELECT * FROM markers";
        $query=$dbh->query($sql);
        foreach ($query=$dbh->query($sql) as $row) 
        {
          $array[]=$rows[] = array(
            "name"=>$row["title"],
          "info"=>$row["desc"],
          "reit"=>$row["reit"],
          "lat"=>$row["sh"],
          "lng"=>$row["dg"]
         );
        }
       $file='places.json';
       $a='{"placesData":';
       $a=$a.json_encode($rows).'}';
       file_put_contents($file, $a);
  }else{
    echo "Вам необходимо авторизироваться";
  }
}
?>

how, what and where should I write in rails to make it work this way?
and it turns out that the document should be created by itself after confirming the sending of the form
, I don’t ask for a solution, but I would like a specific kick in the right direction

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
TyzhSysAdmin, 2016-03-10
@POS_troi

You just don't want to read the documentation and people don't want to teach you the basics.
A POST request in rails is a hash array, we read the ruby ​​docks about json and you will immediately get an answer there.

F
f1int, 2016-03-10
@f1int

If you want to save data in json format, then you can use serialize - it is prescribed for the field that will store data
api.rubyonrails.org/classes/ActiveRecord/Attribute...
To output json to the desired action , call
As an example:

class IndexController < ApplicationController
  def index
    render json: { hellow: :world }
  end
end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question