王筝的博客
ruby学习

 

http://api.rubyonrails.org/classes/ActionView/Template.html#method-i-local_assigns

 

Returns a hash with the defined local variables.

Given this sub template rendering:

<%= render "shared/header", { headline: "Welcome", person: person } %>
You can use local_assigns in the sub templates to access the local variables:

local_assigns[:headline] # => "Welcome"

 

 

 

current_index = local_assigns[:index] || default_index
from = (local_assigns[:from] || default_from) + ["#{current_index}:#{component.name}"]
version = :v4

 

json.array! component.get_parts_in_order(@status).each_with_index.to_a do |part, index|
          json.partial! 'api/v2/components/component', component: part, from: from, index: index
        end

 

 

 

http://api.rubyonrails.org/classes/Array.html#method-i-second

 

[27] pry(main)> list = ["a", "b", "c", "d"]
=> ["a", "b", "c", "d"]
[28] pry(main)> list.first
=> "a"
[29] pry(main)> list.second
=> "b"
[30] pry(main)> list.third
=> "c"
[32] pry(main)> list.second_to_last
=> "c"q

 

 

 

The SanitizeHelper module provides a set of methods for scrubbing text of undesired HTML elements. These helper methods extend Action View making them callable within your template files.

只允许 sanitize 方法中指定的标签和属性输出到页面,防止注入

 

sanitize(html, options = {})

 

Sanitizes HTML input, stripping all tags and attributes that aren’t whitelisted.

It also strips href/src attributes with unsafe protocols like javascript:, while also protecting against attempts to use Unicode, ASCII, and hex character references to work around these protocol filters.

The default sanitizer is Rails::Html::WhiteListSanitizer. See Rails HTML Sanitizers for more information.

Custom sanitization rules can also be provided.

Please note that sanitizing user-provided text does not guarantee that the resulting markup is valid or even well-formed. For example, the output may still contain unescaped characters like <>, or &.

  • :tags – An array of allowed tags.
  • :attributes – An array of allowed attributes.
  • :scrubber – A Rails::Html scrubber or Loofah::Scrubber object that defines custom sanitization rules. A custom scrubber takes precedence over custom tags and attributes.

 

module AnnouncementsHelper
  def safe_content(content)
    sanitize(content, tags: %w(b br))
  end
end

 

 

<p>
  <strong><%= t 'content' %></strong>
  <%= safe_content @announcement.content %>
</p>

 

 

http://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html

在图片管理里添加了校验方法之后,发现在更新的时候页面不显示校验报错的信息

class Picture < ApplicationRecord
 belongs_to :imageable, polymorphic: true

 validates_uniqueness_of :name, scope: [:imageable_id, :imageable_type]
end
~

update!在校验的时候会抛出异常,导致ajax操作中断,

Started PATCH "/components/11" for 127.0.0.1 at 2016-09-06 14:31:08 +0800
Processing by ComponentsController#update as JS
  Parameters: {"utf8"=>"", "component"=>{"name"=>"3131", "alias"=>"", "pictures_attributes"=>[{"id"=>"33", "name"=>"poster", "url"=>"0510000057CE600F6714C06411004555", "md5"=>"9ff2d30b17de8fc75163faff99c18afc"}, {"id"=>"34", "name"=>"poster", "url"=>"0510000057CE60BF6714C063340BE1DC", "md5"=>"c5641765c087043ddc937ac5938c98d2"}, {"name"=>"poster", "url"=>"", "md5"=>""}], "release_id"=>"1", "component_type_id"=>"6", "x_axis"=>"", "y_axis"=>"", "width"=>"", "height"=>"", "unitary"=>"true", "ratio"=>"", "column"=>"", "hints"=>{"left"=>"", "mid"=>"", "right"=>""}, "remark"=>""}, "commit"=>"更新模块", "id"=>"11"}
  User Load (0.3ms)  SELECT  `users`.* FROM `users` WHERE `users`.`id` = 1 ORDER BY `users`.`id` ASC LIMIT 1
  Component Load (0.2ms)  SELECT  `components`.* FROM `components` WHERE `components`.`id` = 11 LIMIT 1
   (0.1ms)  BEGIN
  Picture Load (0.2ms)  SELECT `pictures`.* FROM `pictures` WHERE `pictures`.`imageable_id` = 11 AND `pictures`.`imageable_type` = 'Component' AND `pictures`.`id` IN (33, 34)
  Picture Exists (0.4ms)  SELECT  1 AS one FROM `pictures` WHERE `pictures`.`name` = BINARY 'poster' AND (`pictures`.`id` != 34) AND `pictures`.`imageable_type` = 'Component' LIMIT 1
  Component Exists (0.2ms)  SELECT  1 AS one FROM `components` WHERE `components`.`name` = BINARY '3131' AND (`components`.`id` != 11) AND `components`.`release_id` = 1 LIMIT 1
   (0.2ms)  ROLLBACK
Completed 422 Unprocessable Entity in 23ms (ActiveRecord: 3.4ms)


  
ActiveRecord::RecordInvalid (验证失败: Pictures name已经被使用):
  

原因是在controller的update方法里加了!,变成了update!(component_params), 去掉后的方法如下

  def update
    if @component.update(component_params)
      redirect_to @component, notice: 'Component was successfully updated.'
    else
      render :error
    end 
  end

去掉后的log如下

Started PATCH "/components/11" for 127.0.0.1 at 2016-09-06 15:21:37 +0800
Processing by ComponentsController#update as JS
  Parameters: {"utf8"=>"", "component"=>{"name"=>"3131", "alias"=>"", "pictures_attributes"=>[{"id"=>"33", "name"=>"poster", "url"=>"0510000057CE600F6714C06411004555", "md5"=>"9ff2d30b17de8fc75163faff99c18afc"}, {"id"=>"34", "name"=>"poster", "url"=>"0510000057CE60BF6714C063340BE1DC", "md5"=>"c5641765c087043ddc937ac5938c98d2"}, {"name"=>"poster", "url"=>"", "md5"=>""}], "release_id"=>"1", "component_type_id"=>"6", "x_axis"=>"", "y_axis"=>"", "width"=>"", "height"=>"", "unitary"=>"true", "ratio"=>"", "column"=>"", "hints"=>{"left"=>"", "mid"=>"", "right"=>""}, "remark"=>""}, "commit"=>"更新模块", "id"=>"11"}
  User Load (0.2ms)  SELECT  `users`.* FROM `users` WHERE `users`.`id` = 1 ORDER BY `users`.`id` ASC LIMIT 1
  Component Load (0.1ms)  SELECT  `components`.* FROM `components` WHERE `components`.`id` = 11 LIMIT 1
   (0.1ms)  BEGIN
  Picture Load (0.1ms)  SELECT `pictures`.* FROM `pictures` WHERE `pictures`.`imageable_id` = 11 AND `pictures`.`imageable_type` = 'Component' AND `pictures`.`id` IN (33, 34)
  Picture Exists (0.2ms)  SELECT  1 AS one FROM `pictures` WHERE `pictures`.`name` = BINARY 'poster' AND (`pictures`.`id` != 34) AND `pictures`.`imageable_type` = 'Component' LIMIT 1
  Component Exists (0.2ms)  SELECT  1 AS one FROM `components` WHERE `components`.`name` = BINARY '3131' AND (`components`.`id` != 11) AND `components`.`release_id` = 1 LIMIT 1
   (0.1ms)  ROLLBACK
  Rendering components/error.js.erb
  Picture Load (0.2ms)  SELECT `pictures`.* FROM `pictures` WHERE `pictures`.`imageable_id` = 11 AND `pictures`.`imageable_type` = 'Component'
  Rendered shared/_image.html.erb (2.6ms)
  Rendered shared/_image.html.erb (1.4ms)
  Rendered shared/_image.html.erb (1.5ms)
   (0.2ms)  SELECT `releases`.`version_name`, `releases`.`id` FROM `releases` ORDER BY `releases`.`version_name` DESC
   (0.2ms)  SELECT `component_types`.`name`, `component_types`.`id` FROM `component_types`
  Rendered components/_form.html.erb (36.7ms)
  Rendered components/error.js.erb (52.7ms)
Completed 200 OK in 111ms (Views: 87.3ms | ActiveRecord: 1.6ms)

 

    59: def adjust_sequence
 => 60:   binding.pry
    61:   self.class.
    62:     where(sortable_conditions).
    63:     where('sequence > ?',sequence).update_all("sequence = sequence - 1")
    64: end

 

[1] pry(#<RecommendedVideo>)> sortable_conditions
=> {}
[2] pry(#<RecommendedVideo>)> super.sortable_conditions
NoMethodError: super: no superclass method `adjust_sequence' for #<RecommendedVideo:0x007f11ef8971e8>
from /home/wz/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activemodel-4.2.5/lib/active_model/attribute_methods.rb:430:in `method_missing'
[3] pry(#<RecommendedVideo>)> self
=> #<RecommendedVideo:0x007f11ef8971e8
 id: 28,
 video_id: "XODI0OA==",
 url: "",
 title: "最美是你 TV版",
 video_type: "show",
 version: "",
 homepage_channel_id: "2",
 created_by: "",
 updated_by: "",
 current_update: "",
 show_id: "ad054ed6d9e911e0a046",
 pay_type: "0",
 paid: "0",
 state: 0,
 sequence: 1,
 created_at: Thu, 24 Mar 2016 18:27:05 CST +08:00,
 updated_at: Thu, 24 Mar 2016 18:56:23 CST +08:00>
[4] pry(#<RecommendedVideo>)> self.sortable_conditions
NoMethodError: private method `sortable_conditions' called for #<RecommendedVideo:0x007f11ef8971e8>
from /home/wz/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/activemodel-4.2.5/lib/active_model/attribute_methods.rb:430:in `method_missing'

原因是私有方法不能显示的调用

[14] pry(#<RecommendedVideo>)> self.send :sortable_conditions
=> {}

 

查看方法调用及方法所在处

[10] pry(#<RecommendedVideo>)> self.class.instance_method :sortable_conditions
=> #<UnboundMethod: RecommendedVideo#sortable_conditions>
[11] pry(#<RecommendedVideo>)> m = self.class.instance_method :sortable_conditions
=> #<UnboundMethod: RecommendedVideo#sortable_conditions>
[12] pry(#<RecommendedVideo>)> m.source
=> "    def sortable_conditions\n      {}\n    end\n"
[13] pry(#<RecommendedVideo>)> m.source_location
=> ["/home/wz/workspace/ott-remote-cms/app/models/recommended_video.rb", 123]

 

channel_type对应多种类型,每个类型在数据库中存储的字段和在页面上显示的字段是不同的,

如果在index里直接使用 select_tag 方法,是这样的:

<%= select_tag "channel_type", options_for_select([['信号源', 'signal_source'],
['直播轮播', 'live_and_rotate'],
['我的','my_channel'],
['cibn频道','cibn_channel']],@launcher_channel.channel_type) %>

不过这个下拉菜单显得有些多余,

可以在model里加一个方法,

  def channel_type_human
    {   
      signal_source:  '信号源',
      live_and_rotate:  '直播轮播',
      my_channel:  '我的',
      cibn_channel:  'cibn频道'
    }[channel_type.to_sym]
  end 

再 view 中,直接调用 channel.channel_type_human 就可以啦

 

部署新服务器之后发现,服务器上没有console命令了

root@i-1lb6pxls:/home/ubuntu/campo/current# bundle exec rails c
Usage:
  rails new APP_PATH [options]

Options:
  -r, [--ruby=PATH]                                      # Path to the Ruby binary of your choice
                                                         # Default: /usr/local/rvm/rubies/ruby-2.0.0-p643/bin/ruby
  -m, [--template=TEMPLATE]                              # Path to some application template (can be a filesystem path or URL)
      [--skip-gemfile], [--no-skip-gemfile]              # Don't create a Gemfile
  -B, [--skip-bundle], [--no-skip-bundle]                # Don't run bundle install
  -G, [--skip-git], [--no-skip-git]                      # Skip .gitignore file
      [--skip-keeps], [--no-skip-keeps]                  # Skip source control .keep files
  -O, [--skip-active-record], [--no-skip-active-record]  # Skip Active Record files
  -V, [--skip-action-view], [--no-skip-action-view]      # Skip Action View files
  -S, [--skip-sprockets], [--no-skip-sprockets]          # Skip Sprockets files
      [--skip-spring], [--no-skip-spring]                # Don't install Spring application preloader
  -d, [--database=DATABASE]                              # Preconfigure for selected database (options: mysql/oracle/postgresql/sqlite3/frontbase/ibm_db/sqlserver/jdbcmysql/jdbcsqlite3/jdbcpostgresql/jdbc)
                                                         # Default: sqlite3
  -j, [--javascript=JAVASCRIPT]                          # Preconfigure for selected JavaScript library
                                                         # Default: jquery
  -J, [--skip-javascript], [--no-skip-javascript]        # Skip JavaScript files
      [--dev], [--no-dev]                                # Setup the application with Gemfile pointing to your Rails checkout
      [--edge], [--no-edge]                              # Setup the application with Gemfile pointing to Rails repository
  -T, [--skip-test-unit], [--no-skip-test-unit]          # Skip Test::Unit files
      [--rc=RC]                                          # Path to file containing extra configuration options for rails command
      [--no-rc], [--no-no-rc]                            # Skip loading of extra configuration options from .railsrc file

Runtime options:
  -f, [--force]                    # Overwrite files that already exist
  -p, [--pretend], [--no-pretend]  # Run but do not make any changes
  -q, [--quiet], [--no-quiet]      # Suppress status output
  -s, [--skip], [--no-skip]        # Skip files that already exist

Rails options:
  -h, [--help], [--no-help]        # Show this help message and quit
  -v, [--version], [--no-version]  # Show Rails version number and quit

Description:
    The 'rails new' command creates a new Rails application with a default
    directory structure and configuration at the path you specify.

    You can specify extra command-line arguments to be used every time
    'rails new' runs in the .railsrc configuration file in your home directory.

    Note that the arguments specified in the .railsrc file don't affect the
    defaults values shown above in this help message.

Example:
    rails new ~/Code/Ruby/weblog

    This generates a skeletal Rails installation in ~/Code/Ruby/weblog.
    See the README in the newly created application to get going.

看了一下文件发现bin目录有个软链接,

root@i-1lb6pxls:/home/ubuntu/campo/current# ls -al
total 136
drwxr-xr-x 12 root root  4096 Aug 24 18:12 .
drwxr-xr-x  7 root root  4096 Aug 24 18:12 ..
drwxrwxr-x 10 root root  4096 Aug 18 16:23 app
-rw-r--r--  1 root root 26401 Aug 24 18:12 assets_manifest_backup
lrwxrwxrwx  1 root root    29 Aug 24 18:12 bin -> /home/ubuntu/campo/shared/bin
drwxrwxr-x  2 root root  4096 Aug 24 18:12 .bundle
-rw-rw-r--  1 root root   386 Aug 18 16:23 Capfile
-rw-rw-r--  1 root root   337 Aug 18 16:23 CHANGELOG.md
drwxrwxr-x  5 root root  4096 Aug 24 18:12 config
-rw-rw-r--  1 root root   154 Aug 18 16:23 config.ru
drwxrwxr-x  3 root root  4096 Aug 18 16:23 db
-rw-rw-r--  1 root root  2988 Aug 18 16:23 Gemfile
-rw-rw-r--  1 root root  9758 Aug 18 16:23 Gemfile.lock
-rw-rw-r--  1 root root   727 Aug 18 16:23 .gitignore
-rw-rw-r--  1 root root   459 Aug 18 16:23 Guardfile
drwxrwxr-x  4 root root  4096 Aug 18 16:23 lib
-rw-rw-r--  1 root root  1128 Aug 18 16:23 LICENSE.md
lrwxrwxrwx  1 root root    29 Aug 24 18:12 log -> /home/ubuntu/campo/shared/log
drwxrwxr-x  2 root root  4096 Aug 24 18:12 public
-rw-rw-r--  1 root root   249 Aug 18 16:23 Rakefile
-rw-rw-r--  1 root root   258 Aug 18 16:23 README.md
-rw-rw-r--  1 root root    11 Aug 18 16:23 .ruby-version
drwxrwxr-x  2 root root  4096 Aug 18 16:23 script
drwxrwxr-x 11 root root  4096 Aug 18 16:23 test
drwxr-xr-x  2 root root  4096 Aug 24 18:12 tmp
-rw-rw-r--  1 root root   438 Aug 18 16:23 .travis.yml
-rw-rw-r--  1 root root   615 Aug 18 16:23 Vagrantfile
drwxrwxr-x  3 root root  4096 Aug 24 18:12 vendor

先删除了链接

# rm bin

然后再新建个文件夹重新生成一下目录的内容就ok啦

root@i-1lb6pxls:/home/ubuntu/campo/current# mkdir bin
root@i-1lb6pxls:/home/ubuntu/campo/current# rake rails:update:bin
       exist  bin
      create  bin/bundle
      create  bin/rails
      create  bin/rake

如果记不清rake命令了可以查一下

root@i-1lb6pxls:/home/ubuntu/campo/current# rake -T
rake about                              # List versions of all Rails frameworks and the environment
rake assets:clean[keep]                 # Remove old compiled assets
rake assets:clobber                     # Remove compiled assets
rake assets:environment                 # Load asset compile environment
rake assets:precompile                  # Compile all the assets named in config.assets.precompile
rake cache_digests:dependencies         # Lookup first-level dependencies for TEMPLATE (like messages/show or comments/_comment.html)
rake cache_digests:nested_dependencies  # Lookup nested dependencies for TEMPLATE (like messages/show or comments/_comment.html)
rake db:create                          # Creates the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:create:...
rake db:drop                            # Drops the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:drop:all ...
rake db:fixtures:load                   # Load fixtures into the current environment's database
rake db:migrate                         # Migrate the database (options: VERSION=x, VERBOSE=false, SCOPE=blog)
rake db:migrate:status                  # Display status of migrations
rake db:populate                        # Fill database with sample data
rake db:rollback                        # Rolls the schema back to the previous version (specify steps w/ STEP=n)
rake db:schema:cache:clear              # Clear a db/schema_cache.dump file
rake db:schema:cache:dump               # Create a db/schema_cache.dump file
rake db:schema:dump                     # Create a db/schema.rb file that is portable against any DB supported by AR
rake db:schema:load                     # Load a schema.rb file into the database
rake db:seed                            # Load the seed data from db/seeds.rb
rake db:send_invitations                # send_invitations_to_all
rake db:setup                           # Create the database, load the schema, and initialize with the seed data (use db:reset to also drop the ...
rake db:structure:dump                  # Dump the database structure to db/structure.sql
rake db:version                         # Retrieves the current schema version number
rake doc:app                            # Generate docs for the app -- also available doc:rails, doc:guides (options: TEMPLATE=/rdoc-template.rb,...
rake elasticsearch:import:all           # Import all indices from `app/models` (or use DIR environment variable)
rake elasticsearch:import:model         # Import data from your model (pass name as CLASS environment variable)
rake log:clear                          # Truncates all *.log files in log/ to zero bytes (specify which logs with LOGS=test,development)
rake middleware                         # Prints out your Rack middleware stack
rake notes                              # Enumerate all annotations (use notes:optimize, :fixme, :todo for focus)
rake notes:custom                       # Enumerate a custom annotation, specify with ANNOTATION=CUSTOM
rake rails:template                     # Applies the template supplied by LOCATION=(/path/to/template) or URL
rake rails:update                       # Update configs and some other initially generated files (or use just update:configs or update:bin)
rake rails_admin:install                # Install rails_admin
rake rails_admin:prepare_ci_env         # CI env for Travis
rake rails_admin:uninstall              # Uninstall rails_admin
rake resque:failures:sort               # Sort the 'failed' queue for the redis_multi_queue failure backend
rake resque:work                        # Start a Resque worker
rake resque:workers                     # Start multiple Resque workers
rake routes                             # Print out all defined routes in match order, with names
rake secret                             # Generate a cryptographically secure secret key (this is typically used to generate a secret for cookie ...
rake stats                              # Report code statistics (KLOCs, etc) from the application
rake test                               # Runs test:units, test:functionals, test:generators, test:integration together
rake test:all                           # Run tests quickly by merging all types and not resetting db
rake test:all:db                        # Run tests quickly, but also reset db
rake time:zones:all                     # Displays all time zones, also available: time:zones:us, time:zones:local -- filter with OFFSET paramete...
rake tmp:clear                          # Clear session, cache, and socket files from tmp/ (narrow w/ tmp:sessions:clear, tmp:cache:clear, tmp:so...
rake tmp:create                         # Creates tmp directories for sessions, cache, sockets, and pids

接下来就可以运行console啦

RAILS_ENV=staging bundle exec rails c

 

url_hash.sort_by {|k| k[“title”]}

http://stackoverflow.com/questions/3154111/how-do-i-sort-an-array-of-hashes-by-a-value-in-the-hash

#这段话可以由下面的话替代
56     respond_to do |format|
57       if @video.save
58         format.html { redirect_to(:action => “index”, :forminfo => @subject) }
59       else
60         format.html { render :action => “new” }
61       end
62     end
63     #用于替代上面的方法
64     if @video.save
65       redirect_to(:action => “index”, :forminfo => @subject)
66     else
67       render :action => “new”
68     end

 

#以下的方法可以由下面的方法替代
102 respond_to do |format|
103 format.html { redirect_to(:action => ‘index’, :forminfo => @subject) }
104 format.xml { head :ok }
105 end
106 #用于替代上面的方法
107 redirect_to(:action => ‘index’, :forminfo => @subject)