Tag Archive for rails

Regenerate paperclip thumbnails

# Given Asset has_attached_file
Asset.find(:all).each { |a| a.asset.reprocess!; a.save }

source

Rails Nested Forms with belongs_to

# user.rb

class User < ActiveRecord::Base
  belongs_to :address
  accepts_nested_attributes_for :address # can't have allow_destroy
end

# users_controller.rb

class UsersController < ApplicationController
  resource_controller
  before_filter :load_object, :except => :index
  
  # called at the beginning of each action
  def load_object
    @user = User.find(...)
    @user.address ||= Address.new()
    @user
  end
end

# users/edit.html.erb

<% form_for(@user, :url => collection_url) do |f| %>
  <%= render :partial => "form", :locals => { :f => f } %>
  <p>
    <%= submit_tag t("create"), {"class" => "wymupdate"}%>
  </p>
<% end %>

# users/_form.html.erb

<table class="admin-report" width="545">
	<fieldset id='name'>
	    <div class="inner">
	      <p class="field">&nbsp;</p>
	      <p id="aname" class="field">
	        <%= f.label :name, t(:name) %><br />
	        <%= f.text_field :name, :class => 'required' -%><span class="req">*</span>
	      </p>
		</div>
	</fieldset>
	<%= render :partial => "address_form", :locals => { :f => f } %>
</table>

# users/_address_form.html.erb

<fieldset id='address'>
  <% f.fields_for :address do |address_form| %>
    <legend><%= t("address")%></legend>
    <div class="inner">
      <p class="field">&nbsp;</p>
      <p id="afname" class="field">
        <%= address_form.label :firstname, t(:first_name) %><br />
        <%= address_form.text_field :firstname, :class => 'required' -%><span class="req">*</span>
      </p>
    </div>
  <% end %>
</fieldset>

source

RoR – Select Box Using Existing Model

# Replace |model| with whatever you want to use. ie. |whatever|
<%= select(:object, :name, Model.all.collect {|model| [model.name, model.id]}) %>

source

generate a mysql BETWEEN clause to find within a date range

def mysql_date_compare(start_date, end_date, col_name = :created_at)
  range_start = (Date.parse(start_date.to_s) - 1.day).strftime("%Y-%m-%d 23:59:59")
  range_end = (Date.parse(end_date.to_s) + 1.day).strftime("%Y-%m-%d 00:00:00")
  "#{col_name.to_s} BETWEEN '#{range_start}' AND '#{range_end}'"
end

source

ruby on rails install in ubuntu

1.step----------------------

sudo apt-get install ruby-full build-essential libruby-extras libsqlite3-ruby

2.step---------------------

wget <a href="http://rubyforge.org/frs/download.php/60718/rubygems-1.3.5.tgz" >http://rubyforge.org/frs/download.php/60718/rubygems-1.3.5.tgz</a>
tar xzvf rubygems-1.3.5.tgz
cd rubygems-1.3.5
sudo ruby setup.rb

3.step--------------------

sudo gem install rails

source

Synchronize local mysql database to remote mysql database

namespace :db do
task :sync_to_local, :roles => :web do
  sql_out = "#{environment_database}.sql"
  run "mysqldump --user #{dbuser} --password=#{dbpass} #{environment_database} > #{sql_out}"
  system "sftp #{user}@myhost.com:#{sql_out} /tmp/#{sql_out}"
  run "rm #{sql_out}"
  system "mysql -u #{dbuser} --password=#{dbpass} mydatabase_development < /tmp/#{sql_out}"
  system "rm /tmp/#{sql_out}"
end
end

# invoked: cap production db:sync_to_local

source

Backup a mysql database script

#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../config/boot'
require 'erb'
require 'yaml'

unless config = YAML::load(ERB.new(IO.read(RAILS_ROOT + "/config/database.yml")).result)[RAILS_ENV]
  abort "No database is configured for the environment '#{RAILS_ENV}'"
end

db_out_path = File.join(RAILS_ROOT, 'tmp', "dbdump_#{RAILS_ENV}.sql")
system "mysqldump -u #{config['username']} --password=#{config['password']} #{config['database']} > #{db_out_path}"

source

will_paginate with jquery ajax / постаничный вывод в Rails с will_paginate и Jquery

//ajax function-------------------------------------

function ajax_will_paginate(s){
  $.ajax({
  type: "POST",
  url: "index/blog_paginate?page="+s,
  success: function(msg){
    $("div.blog[style='display: block;']").html(msg);
    replace_paginate_links();
  }
  });
}

// replace links function---------------------------

function replace_paginate_links(){
  $('div.pagination a').each(function(){
  var new_attr = "ajax_will_paginate"
  var get_href_a = $(this).attr('href').split('=');
  var get_href = get_href_a[get_href_a.length-1]

  $(this).attr('href',"#")
  $(this).attr('onclick',"ajax_will_paginate('"+get_href+"'); return false;")
})
}

$(document).ready(function(){
  replace_paginate_links()
})

source

rails file upload/ выгрузка файла в ruby on rails 2+

source of file model *DataFile.rb* / Код класса DataFile.rb, который нужно создать в папке models


require 'rutils'

def self.save(upload)
  spl = upload['datafile'].original_filename.split('.')
  ext = spl[spl.length-1]

  name =  File.basename(upload['datafile'].original_filename).gsub(/.#{ext}/,'').dirify<<'.'<<ext 

  directory = "htdocs/images"
  # create the file path
  path = File.join(directory, name)
  # write the file
  File.open(path, "wb") { |f| f.write(upload['datafile'].read) }
  return name
end



-----------------------------
uploading form view / форма выгрузки файла

<form action="/anycontrooller/upload_action" enctype="multipart/form-data" method="post">
  <p><input id="upload_datafile" name="upload[datafile]" size="30" type="file" /></p>
  <input name="commit" type="submit" value="Upload" />
</form>

---------------------------------
Принимающий контроллер / receiving controller

def upload

 begin
  post = DataFile.save(params[:upload])
  render :text =>'Файл был успешно выложен под именем <br />"<b>'<<post.to_s+'</b>"'
 rescue
  render :text =>'error'
 end

end

source

view logs online in ROR, using ssh / следим за логами через SSH

tail -f log/production.log

source