1.routes.rb에 import path를 추가한다.

 resources 'wifi_each_info', controller: 'device/wifi_settings/wifi_each_info' do 

      collection { post:import} #post로 추가한다.

    end

2.view 에서 하기와 같이 추가

<%= form_tag(import_wifi_each_info_index_path, multipart:true) do %>

          <%= file_field_tag :file %>

          <%= submit_tag "Import CSV" %>

          <% end %>


이때 file_field와 file_field_tag 는 기능상의 차이가 없다!!


3. controller에서 model을 호출한다.

def import

    logger.debug "controller====#{params.inspect}"

    if params[:file].present?

      logger.debug "controller====#{params[:file].original_filename}"

      DeviceWifiInfo.import(params[:file])    

      redirect_to wifi_common_index_path, notice:  I18n.t('table.label.wifi_settings.each_info.completed_csv')

    else

      redirect_to wifi_common_index_path, alert:  I18n.t('table.label.wifi_settings.each_info.failed_csv')

    end

  end  


4. model에서 import를 구현한다.

def self.import(file)

  logger.debug "====model = #{file.inspect}"

    logger.debug "self.import"


  CSV.foreach(file.path, headers: true,  :encoding => 'ISO-8859-1') do |row|      

  logger.debug "===#{row.inspect}"

      #1 create wifi infi not considering duplicate      

      if row["DHCP"] == "1" #row안에 있는 속성은 ""으로 묶어서 읽는다. 속성은 csv 헤더에서 읽어온다

        dhcp = true       

        logger.debug "dhcp true"

      else

        dhcp = false

        logger.debug "dhcp false"

      end

      wifi_info_new = DeviceWifiInfo.new(dhcp: dhcp,static_ip: row["static_ip"], static_subnet: row["static_subnet"],

        static_gateway: row["static_gateway"], account_id: row["account_id"], account_password: row["account_password"],

        serial_id: row["serial_id"])

      wifi_info_new.save      

        end

      end

  end



by 무위자연 2016. 12. 8. 11:52

환경 설정 파일(development/production 등)


config.logger = Logger.new('./log/production.log', 'daily')

뒤에 옵션에 daily / weekly 등을 넣어주면 된다.

by 무위자연 2016. 9. 19. 19:57
- 영문으로 db:reset할 때는  config / application.rb에서 default_locale과 time_zone을 설정한다.
 config.time_zone = 'Seoul'
  # config.active_record.default_timezone = 'Seoul'
  config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.yml').to_s]
  config.i18n.default_locale = :ko


by 무위자연 2016. 8. 23. 16:32
route.rb에서 지원여부만 넣어주면 끝.
컨트롤러의 액션에서는 사용자로부터 전송된 데이터나 그 이외의 파라미터를 사용하여 어떤 작업을 하는 경우가 많습니다. Rails 뿐만이 아니라, 일반적인 웹 애플리케이션에서는 2종류의 파라미터를 사용할 수 있습니다. 첫번째는 URL의 일부로서 전송되는 파라미터로서, '쿼리 문자열 파라미터'라고 부릅니다. 쿼리 문자열은 URL의 "?"의 뒤에 위치합니다. 두번째는 'POST 데이터'라고 불리는 것입니다. POST 데이터는 보통 사용자가 기입한 HTML 폼으로부터 전송됩니다. 이는 HTTP POST 요청의 일부로 전송되기 때문에 POST 데이터라고 불립니다. Rails에서의 쿼리 문자열 파라미터와 POST 데이터를 다루는 방식에는 차이가 없습니다. 어느 쪽도 컨트롤러 내부에서는 params라는 이름의 해시를 통해 접근할 수 있습니다.

ex.

route.rb에서 다음과 같이 추가한다.

get 'checkversion' => 'api#checkversion'

post 'checkversion' => 'api#checkversion'


controller에서는 분기처리 없이 다음과 같이 공통 코드를 사용한다.


 def checkversion

    begin

    logger.debug("checkversion")     

    ip_info = params[:ip] 

    #.....


end

by 무위자연 2016. 8. 22. 10:18



배열에서 특정 값이 있는지 확인하는 방법


>> ['Cat', 'Dog', 'Bird'].include? 'Dog'

=> true


 unless reg_ids.include? w.base_ward_id

by 무위자연 2016. 4. 27. 11:00


간단한건데 참 안된다. 


check_box_tag 용례도 잘 모르겠고 


해서...


<input type="checkbox" name="cancel"> > 이렇게 tag 를 추가하고



var cancelstr = $("input[name='cancel']").prop("checked"); > prop으로 checked 상태를 받아올 수 있다.

       console.log("====cancelstr : " + cancelstr);

       if(cancelstr == false)

       {

          console.log("====cancelstr!!!!!!!!!!!!!!");

       }

       else

       {

          console.log("====TTTTTTTTT");

       }

by 무위자연 2016. 4. 19. 17:56

임시 방편으로


해당 .rb 파일에서 직접 생성해서 사용한다.


logger = Logger.new(STDOUT)

logger.debug "initialize=======================================(+)"


by 무위자연 2016. 4. 19. 13:32

 logger.debug "check public/uploads"

      Dir.mkdir("public/uploads") unless Dir.exist?("public/uploads")

      logger.debug "check public/uploads/tmp"

      Dir.mkdir("public/uploads/tmp") unless Dir.exist?("public/uploads/tmp")


한번에 2 depth를 생성할 수는 없는 것 처럼 동작한다.

옵션이 있을지 모르지만.


일단 폴더 확인 로직 추가한다.



by 무위자연 2016. 4. 11. 17:54



stuff - a local variable : 해당 모듈 혹은 action 이내에서만 처리가능한 선언

  
@stuff - an object variable (one per object) - 해당 모듈 뿐 아니리 연결된 html.erb에서도 사용할 수 있는 선언


@@stuff - a class variable (just one for a whole class of objects) - @와 뭐가 다른지 더 고민해야 함.


$stuff - a global variable (just one for the program) - 마치 응용프로그램의 전역변수 처럼 동작하는데 그 메모리 해제나 기타 이슈가 있는지 확인해야 한다.

by 무위자연 2016. 4. 8. 16:15
방법은 두 가지가 있다.

1. rails generate model - 명령어로 모델과 함께 생성 - 모델을 생성한다.
ex. rails generate model device_wifi_info mac_address:string{16} dhcp:boolean dm_port:integer

다음과 같이 index를 추가하면 DB에 index가 붙게 되고 migration 파일에 다음과 같이 추가된다.
rails generate model people patient_id:string:index

migration 파일에선:
       add_index :people, :patient_id
DB에선:
     INDEX `index_people_on_patient_id` (`patient_id`) USING BTREE

2. rails generate migration - 명령어를 사용해서 마이그레이션 파일만 생성 - 기존 모델을 update한다.
AddXxxxxTo<테이블이름> - 필드 추가
ex 
rails generate migration AddDeletedAtToDevice deleted_at:datetime:index
deleted_at이란 datetime 필드에 index도 추가하게 한다.
결과 파일은 다음과 같다.
----------------------------
class AddDeletedAtToDevice < ActiveRecord::Migration
  def change
    add_column :devices, :deleted_at, :datetime
    add_index :devices, :deleted_at
  end
end
------------------------------


RemoveXxxxxFrom<테이블 이름> - 필드 제거
rails generate migration RemoveColumnPolicyPermFromPermissions policy_menu_perm:integer

3. scaffold로 생성하기  : Model  + View + Controller
ex. rails generate scaffold Post name:string title:string content:text



by 무위자연 2016. 3. 21. 10:08
| 1 2 |