小编Sea*_*yar的帖子

Rails text_field / text_ara 空字符串与 nil

我什至不确定我是否有问题,但我只是不喜欢我的 text_fields 和 text_areas 保存在数据库中而empty string不是nil.

我正在使用空对象模式,刚刚意识到如果我创建一个配置文件但不填写位置字段然后调用<%= @user.profile.location.upcase %>它就不会爆炸,因为位置是一个字符串,即使它是空的。

这是 Rails 的惯例吗?如果是这样,那为什么呢?这有点奇怪,因为假设个人number_of_pets资料上有一个 attr,然后我尝试调用类似的东西

<% if user.profile.number_of_pets.odd? %>
  <%= @user.profile.first_name %> has odd number of pets
<% end %>
Run Code Online (Sandbox Code Playgroud)

然后事情就爆发了,因为我无法打电话nil.odd?

形式如常,所以如果不填写,将保存为空字符串

<%= form_for @profile, url: user_profile_path do |f| %>
  <%= f.label :city %>
  <%= f.text_field :location, class: 'form-control' %>
  ......
Run Code Online (Sandbox Code Playgroud)

database null ruby-on-rails null-object-pattern

5
推荐指数
1
解决办法
3910
查看次数

将服务工作者添加到reactjs应用程序

我是关于创建一个小的单页reactjs应用程序,从第三个API获取数据(让我们说youtube视频,所以这些将显示).所以我根本不需要任何后端,但我想首先让服务工作者离线,所以如果没有连接,默认情况下它仍会显示一些缓存数据.为此,我将使用服务工作者,但不知道我是否必须添加任何其他库,或者我可以立即使用它.

有人能告诉我实施这个小型离线优先反应应用程序的最佳方法是什么?

offline offline-caching reactjs service-worker

5
推荐指数
1
解决办法
2779
查看次数

rails 从机架渲染 html

我正在使用机架攻击。如果有人超过限制,我将使用以下代码:

Rack::Attack.throttled_response = lambda do |env|
  [429, {}, [ActionView::Base.new.render(file: 'public/429.html')]]
end
Run Code Online (Sandbox Code Playgroud)

当 sby 超过原始响应的 POST 请求的限制时respond_to :html,渲染429.html工作正常。当响应的 POST 请求超过限制respond_to :js时,屏幕上没有任何反应,但如果我查看日志,一切似乎都很好:

Rendered public/429.html (1.4ms)
Run Code Online (Sandbox Code Playgroud)

429.html在 的情况下如何显示js response?是否有可能以error messages某种方式从这个机架代码传递到 rails 应用程序?如果不是那么复杂,我可能会更改为error messagesfrom rendering

ruby rendering rack ruby-on-rails rackattack

4
推荐指数
1
解决办法
1272
查看次数

rails4集合通过关联和嵌套模型表单选择has_many

我有一个rails4应用程序.目前,我的收藏选择仅在我选择一个选项时才有效.以下是我的工作代码.我只有产品表格.行业模型填充seeds.rb.IndustryProduct仅用于连接其他2个型号.

我想知道我必须在代码中更改哪些内容才能选择更多内容.

我看到一些工作示例的multiple: true选项如(https://www.youtube.com/watch?v=ZNrNGTe2Zqk 10:20)但在这种情况下,用户界面有点难看+无法用任何样本将其拉下来码.是否还有其他解决方案,例如选择一个选项而不是一个包含多个选项的方框?

楷模:

class Product < ActiveRecord::Base
  belongs_to :user
  has_many :industry_products
  has_many :industries, through: :industry_products
  has_many :product_features

  accepts_nested_attributes_for :industry_products, allow_destroy: true
  accepts_nested_attributes_for :product_features

  validates_associated :industry_products
  validates_associated :product_features
end

class Industry < ActiveRecord::Base
  has_many :industry_products
  has_many :products, through: :industry_products

  accepts_nested_attributes_for :industry_products
end

class IndustryProduct < ActiveRecord::Base
  belongs_to :product
  belongs_to :industry
end
Run Code Online (Sandbox Code Playgroud)

_form.html.erb

<%= form_for @product do |f| %>
  <%= render 'layouts/error_messages', object: f.object %>
  ......
  <%= f.fields_for :industry_products do |p| %>
    <%= p.collection_select …
Run Code Online (Sandbox Code Playgroud)

forms activerecord ruby-on-rails nested-attributes collection-select

3
推荐指数
1
解决办法
4383
查看次数

rails4采用订单和限制

在我的侧边栏中,我显示了新创建的用户配置文件.个人资料belongs_to用户和用户has_one_profile.我意识到我只使用配置文件表中的3列,所以最好使用pluck.我也有link_to user_path(profile.user)部分,所以我不得不告诉用户是谁.目前我正在使用includes,但我不需要整个用户表.所以我使用了来自用户和配置文件表的许多列.

如何用拔毛来优化它?我尝试了几个版本,但总是遇到一些错误(大部分时间都没有定义profile.user).

我目前的代码:

def set_sidebar_users
  @profiles_sidebar = Profile.order(created_at: :desc).includes(:user).limit(3) if user_signed_in?
end

create_table "profiles", force: :cascade do |t|
  t.integer  "user_id",      null: false
  t.string   "first_name",   null: false
  t.string   "last_name",    null: false
  t.string   "company",      null: false
  t.string   "job_title",    null: false
  t.string   "phone_number"
  t.text     "description"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.string   "avatar"
  t.string   "location"
end
Run Code Online (Sandbox Code Playgroud)

sorting activerecord ruby-on-rails pluck

2
推荐指数
1
解决办法
3890
查看次数

使用关键字 args 进行 ruby​​ 初始化

我正在阅读 POODR 书,它使用旧语法进行默认值初始化。我想用新语法实现相同的功能。

class Gear
  attr_reader :chainring, :cog, :wheel
  def initialize(args)
    @chainring = args.fetch(:chainring, 40)
    @cog =  args.fetch(:cog, 10)
    @wheel = args[:wheel]
  end

  def gear_inches
    ratio * diameter
  end

  def diameter
    wheel * diameter
  end
end

Gear.new(chainring: 52, cog: 11, wheel: Wheel.new(26,1.5)).gear_inches
Run Code Online (Sandbox Code Playgroud)

使用新的关键字 args 会是什么样子?这是我在下面的猜测,但不确定它是否与上述车轮的结果相同。

class Gear
  attr_reader :chainring, :cog, :wheel
  def initialize(chainring: 40, cog: 10, wheel:) #is this good here for wheel?
    @chainring = chainring
    @cog = cog
    @wheel = wheel #is this good here for wheel?
  end

  ...... …
Run Code Online (Sandbox Code Playgroud)

ruby constructor initialization keyword-argument

2
推荐指数
1
解决办法
1762
查看次数

理解js中的fetch

我检查了一些资源,但没有真正得到fetch方法.

2 then-s有什么意义?第一个和第二个then好处是什么?为什么是return第一个?

fetch('http://some-site.com/cors-enabled/some.json')  
  .then(function(response) {  
    return response.text();  
  })  
  .then(function(text) {  
    console.log('Request successful', text);  
  })  
  .catch(function(error) {  
    log('Request failed', error)  
  });
Run Code Online (Sandbox Code Playgroud)

javascript fetch promise service-worker

2
推荐指数
1
解决办法
477
查看次数

Rails:gem文件/ bundle install with gem'bootstrap-sass'

我将这行添加到gem文件中:

gem 'bootstrap-sass'        '3.3.2.0'
Run Code Online (Sandbox Code Playgroud)

然后我得到了:

$ bundle install 
Fetching gem metadata from https://rubygems.org/........... 
Fetching additional metadata from https://rubygems.org/.. 
Resolving dependencies... 
Could not find gem 'bootstrap-sass3.3.2.0 (>= 0) ruby' in the gems available on this machine.
Run Code Online (Sandbox Code Playgroud)

所以我从rubygems.org下载并安装它:

$ gem install bootstrap-sass -v 3.3.2.0
Fetching: autoprefixer-rails-5.1.11.gem (100%)
Successfully installed autoprefixer-rails-5.1.11
Fetching: bootstrap-sass-3.3.2.0.gem (100%)
Successfully installed bootstrap-sass-3.3.2.0
2 gems installed
Run Code Online (Sandbox Code Playgroud)

然后尝试:

$bundle install
or/and
$bundle update
Run Code Online (Sandbox Code Playgroud)

仍然收到消息:

Could not find gem 'bootstrap-sass3.3.2.0 (>= 0) ruby' in the gems available on this machine.
Run Code Online (Sandbox Code Playgroud)

我该怎么办?

ruby-on-rails twitter-bootstrap

1
推荐指数
1
解决办法
478
查看次数

将模型的名称添加到Rails中的字符串

我想在rails app中显示以下内容:

Product instance => "product"
ProductCustomer instance => "product customer"
Run Code Online (Sandbox Code Playgroud)

所以我能做到

<%= form_for([commentable, Comment.new]) do |f| %>
  <%= f.text_field :body, class: "form-control", id: "comment-text-area-#{commentable.id}", 
    placeholder: "Ask something about the #{commentable.class.name.split(/(?=[A-Z])/).join(' ').downcase }" %>
  ......
<% end %>
Run Code Online (Sandbox Code Playgroud)

目前我正在使用以下适用于所有情况的:

p = Product.new
p.class.name.split(/(?=[A-Z])/).join(' ').downcase

pc = ProductCustomer.new
pc.class.name.split(/(?=[A-Z])/).join(' ').downcase
Run Code Online (Sandbox Code Playgroud)

我的问题是它看起来太复杂了.我想应该有更好的方法.有任何想法吗?

ruby ruby-on-rails

1
推荐指数
1
解决办法
168
查看次数

rails何时使用|| =设置实例变量

我正在阅读一篇文章,并遇到了第一个示例代码.在模型中,设置实例变量以避免不必要的查询.我也在其中一个railscast中看到了这个(第二个例子).另一方面,我在更多的文章中读到,如果我使用这种模式,那么我的应用可能不会是线程安全的,所以我不能利用我的puma网络服务器.

可以告诉我何时/何地应该使用这种模式?

第一个例子:

def first_order_date
  if first_order
    first_order.created_at.to_date
  else
    NullDate.new 'orders'
  end
end

private

def first_order
  @first_order ||= orders.ascend_by_created_at.first
end
Run Code Online (Sandbox Code Playgroud)

第二个例子

def shipping_price
  if total_weight == 0
    0.00
  elsif total_weight <= 3
    8.00
  elsif total_weight <= 5
    10.00
  else
    12.00
  end
end

def total_weight
  @total_weight ||= line_items.to_a.sum(&:weight)
end
Run Code Online (Sandbox Code Playgroud)

更新的问题

第一个例子

正如我所看到的那样,'first_order_date'总是在一个对象上调用(https://robots.thoughtbot.com/rails-refactoring-example-introduce-null-object),所以我并不完全看到额外的查询是如何避免.我确定我错了,但根据我的知识,它可能只是

def first_order_date
  if orders.ascend_by_created_at.first
    first_order.created_at.to_date
  else
    NullDate.new 'orders'
  end
end
Run Code Online (Sandbox Code Playgroud)

或者也可以使用@first_order其他地方?

第二个例子

原始问题中的代码与此不相同?

def shipping_price
  total_weight = line_items.to_a.sum(&:weight)
  if total_weight == 0
    0.00
  elsif total_weight …
Run Code Online (Sandbox Code Playgroud)

ruby conditional ruby-on-rails instance-variables

0
推荐指数
1
解决办法
782
查看次数

如果在类体中调用了方法,如何在Ruby/Rails中进行测试?

我无法想象如何在类体内测试类方法调用.

我该怎么测试呢?

class User
  act_as_paranoid
end


it 'is called from class body' do
  expect(User).to receive(:acts_as_paranoid)
  User.new
end
Run Code Online (Sandbox Code Playgroud)

ruby rspec ruby-on-rails

0
推荐指数
1
解决办法
353
查看次数