jeudi 30 juillet 2015

Assign Subcategories to a Main Category

On my current local blog site I'm able to create both Categories and Subcategories.

I want to make is so when creating a post, once you choose the category from the drop-down, it will only show the available subcategories.

Example:

enter image description here

In this example "News is selected". So I need to do two things. First, assign the subcategories I make to specific categories. Second, display the subcategories accordingly depending on which category is chosen.

Post Model

class Post < ActiveRecord::Base
  belongs_to :category
  belongs_to :subcategory
  has_many :comments

end

New Post View

<h2>Add New Post</h2>

<div class="well">
<%= form_for [:admin, @post] do |f| %>

    <div class="form-group">
        <%= f.label :title %>
        <%= f.text_field :title ,class:'form-control' %>
    </div>

    <div class="form-group">
        <%= f.label :category %>
        <%= f.select :category_id, Category.all.collect {|x| [x.name, x.id]}, {:include_blank => 'Select One'},class:'form-control' %>
    </div>

    <div class="form-group">
        <%= f.label :image %>
        <%= f.file_field :image %>  
    </div>
    <br>

    <div class="form-group">
        <%= f.label :subcategory %>
        <%= f.select :subcategory_id, Subcategory.all.collect {|x| [x.name, x.id]}, {:include_blank => 'Select One'},class:'form-control' %>
    </div>

    <div class="form-group">
        <%= f.label :body %>
        <%= f.text_area :body ,class:'form-control', id:'eg-textarea' %>
    </div>
    <br>
    <%= f.submit "Submit", class:'btn btn-primary' %>
    <%=link_to "Cancel", admin_posts_path, class:'btn btn-default' %>
<% end %>
</div>

Posts Controller

class Admin::PostsController < Admin::ApplicationController
  def new
    @post = Post.new
  end

  def create
    @post = Post.new(post_params)
    @post.save
    redirect_to admin_posts_path
  end

  def edit
  end

  def update
  end

  def index
    @posts = Post.all
  end

  def show
  end

  def destroy
  end

  private
    def post_params
      params.require(:post).permit(:title, :category_id, :subcategory_id, :image, :body)
    end
end

Multiple trip headsigns for a route?

So I just noticed this in my application, but when I get a list of routes that services a stop, I get multiple trip_headsigns for a specific route, but they all run the same route when I get all the stops and the route shape. Am I missing something here? Or can somebody explain why? Here is how I get routes for specific stop:

    SELECT DISTINCT t.trip_headsign, r.route_short_name,r.route_long_name
    FROM stop_times st INNER JOIN trips t
    ON t.trip_id = st.trip_id
    INNER JOIN routes r
    ON r.route_id = t.route_id
    WHERE st.stop_id = <stop_id>

Here is how I get all the stops for a specific route returned by the query

      SELECT DISTINCT t.trip_id, s.stop_code, s.stop_name, s.stop_lat, s.stop_lon, t.shape_id, st.arrival_time
      FROM trips as t INNER JOIN stop_times as st
      ON st.trip_id = t.trip_id
      INNER JOIN stops as s ON s.stop_id = st.stop_id
      WHERE t.route_id = <route_id>
      AND t.service_id = "Weekdays"
      AND t.direction_id = <direction_id>

But as I said, I get multiple trip_headsigns as a query return from the first one, but when I run the second query I get the same route for all those trip_headsigns. Any help/comments/ideas are appreciated!

SQLite DB Getting Incomplete Error

I have a very simple program that I created through SQLite, but when I read the .sql file, I get the error 'incomplete SQL' and then it shows the list twice. Any ideas why this is happening? Thanks!

SQLite need Upgrade on FirstRun

im using SQLite OpenHelper to handle database version and it worked fine, my problem is, if i set some updates and new users install my app, the will not get the UPGRADES, because it will run the onCreate using the last DB_VERSION

explaining:

  private static final int DB_VERSION = 3;

Context context;

public DB(Context c) {

    super(c, DB_NAME, null, DB_VERSION);
    context = c;
}
    public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE table1...");
    }

   @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.d("DBUpgrade", "Atualizando DATABASE");
        switch (oldVersion) {
            case 2: {

            execSQLFromFile(db, "sql2");
            }
  case 3: {

            execSQLFromFile(db, "sql3");
            }


        }

scenarios:

User 1 has installed since first app release -> he will get the all the upgrades

User 2 installed for the first time in his device the last release of my apk that has the db_version 3 -> he will not get the upgrades, just the onCreate

ofc i know why this happens but i dont know how to solve it by a simple way, the only i way i throught was to call the onUpgrade(db, 0, DB_VERSION); this enter in the onUpgrade but dont call the cases inside the switch i dont know why, since i send 0, it should call case: 2, because i dont have the break isnt it?

BUT doing this i loose the OnUpgrade for the next version, it will always check the oldVersion, and redo the same code so it will crash because Unique column, alter columns anything

so i still ended without way to onfirst install do the upgrades too =(

Appcelerator Titanium - Database.install() doesn't working

I'm trying to install sqlite database on native android project. I got the error :

"Cannot call method 'install' of undefined (78:file:///android_asset/Resources/HTML/index.html)"

I tried to call it in different way using a simple js script in the index.html :

    function InstallNULL()
    {
        var db = Titanium.Database.install('dbMacFast', 'dbMacFast');
        if(db != null) alert('dbMacFast works');
    }

    function InstallDB()
    {
        var db = Titanium.Database.install('dbMacFast.db', 'dbMacFast');
        if(db != null) alert('dbMacFast.db works');
    }

    function InstallSQLITE()
    {
        var db = Titanium.Database.install('dbMacFast.sqlite', 'dbMacFast');
        if(db != null) alert('dbMacFast.sqlite works');
    }

Functions are called with buttons and I've put my database in the same folder than my index.html to be sure there is no path problem...

Thanks for help !

Android SQLite Possible Bug: Inserting Date

Here is some code from a database handler class to manage an SQLitedatabase table. The date is inserted as 04082015, but outputs as 40082015, this error does not occur for dates were the day is larger than 10.

I'm creating the table as follows

@Override
public void onCreate(SQLiteDatabase db) {
        String create_college_table = "CREATE TABLE " + TableName + " (" +
                "  `"+KEY_ID+"` INTEGER PRIMARY KEY AUTOINCREMENT,\n" +
                "  `"+KEY_DATE+"` DATETIME NOT NULL UNIQUE,\n" +
                "  `"+KEY_JSON+"` longtext NOT NULL\n" +
                ")";
        db.execSQL(create_college_table);
}

Now, inserting a row into the above table:

public void testit() {
    // write the row into the database:
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues insertValues = new ContentValues();
    // DATE IS FOURTH OF AUGUST 2015
    insertValues.put(KEY_DATE, "04082015");
    insertValues.put(KEY_JSON, "{test}");
    db.insert(
            TableName,
            null,
            insertValues
    );


    // Now read from the database, select the row that was
    // just inserted
    String selectQuery = "SELECT * FROM " + TableName + " " +
            "WHERE " + KEY_JSON + " = '{test}'";
    SQLiteDatabase db_read = this.getWritableDatabase();
    Cursor cursor = db_read.rawQuery(selectQuery, null);
    // Viewing the log the inserted date (04082015) has been
    // outputted as 40082015, this does not occur with dates
    // were the day in the month is ten or larger?!
    Log.e("testMethod", DatabaseUtils.dumpCursorToString(cursor));
}

Android: SQLite Getting all records that inserted in last 7 days

Cursor cursor = db.rawQuery("SELECT * FROM expenses WHERE expense_date > (SELECT DATE('now', '-7 day'));", null);

I have this above query to get all records that inserted in last 7 days. But as a result of this query i am getting all the records. The date column of these records is inserted via Android's DatePicker and they are in 30-Jul-2015 format. I guess that's why this query does not work properly. Is there a way to make them consistent to get this query work properly or i am missing out something else ? Any help would be appreciated.