在Ruby(而不是Rails)中的else if条件中检查变量是否为空的最佳方法是什么?
elsif not variable.to_s.empty?
# do something
end
Run Code Online (Sandbox Code Playgroud)
要么
elsif !variable.to_s.empty?
# do something
end
Run Code Online (Sandbox Code Playgroud)
要么
elsif variable.to_s.length > 0
# do something
end
Run Code Online (Sandbox Code Playgroud) 首先,我得到特定日期之间的审核状态.
date_range = Date.parse(@from_date).beginning_of_day..Date.parse(@to_date).end_of_day
@review_statuses = ReviewStatus.where(updated_at: date_range)
Run Code Online (Sandbox Code Playgroud)
接下来,我需要应用'AND'条件.
@review_cycle = params[:review_cycle]
if @review_cycle.present?
@review_statuses = @review_statuses.merge(
ReviewStatus.where(evidence_cycle: @review_cycle)
.or(ReviewStatus.where(roc_cycle: @review_cycle)))
end
Run Code Online (Sandbox Code Playgroud)
现在,对于下面我应该应用'where'或'merge'.
@status = params[:status]
@review_statuses.where(evidence_status: :pass, roc_status: :pass) if @status == 'pass'
Run Code Online (Sandbox Code Playgroud)
有人可以解释,我们何时应该使用merge而不是where?
我正在尝试实现嵌套模型,这里是路由文件条目:
resources :projects do
resources :instances
end
Run Code Online (Sandbox Code Playgroud)
以下是项目控制器的片段:
# GET /projects/new
def new
@project = Project.new
@project.instances.build
end
Run Code Online (Sandbox Code Playgroud)
和项目的表单视图:
<%= simple_form_for(@project) do |f| %>
...
<%= label_tag :instance_count, "Instance Count" %>
<%= select_tag :instance_count, options_for_select([0, 1, 2, 3, 4, 5], 0) %>
...
<% end %>
Run Code Online (Sandbox Code Playgroud)
现在,当我更改实例计数时,我需要在上面的表单下面多次显示实例字段.这是部分代码:
<%= form.simple_fields_for :instances do |i| %>
...
<% end %>
Run Code Online (Sandbox Code Playgroud)
基本上我需要<%= render 'instances/form', form: f %>从项目的javascript文件中调用.它应该像链接remote: true选项一样工作.但在这种情况下没有链接,但在更改事件时需要显示表单.我该如何实现呢?
这是正在使用的代码 Net::HTTP::Post
request = Net::HTTP::Post.new(url)
...
form_data = [
['attachments[]', File.open('file1.txt')],
['attachments[]', File.open('file2.txt')]
]
request.set_form form_data, 'multipart/form-data'
http.request(request)
Run Code Online (Sandbox Code Playgroud)
现在,我正在尝试httparty像下面这样使用,但是它不起作用。
body = { attachments: [ File.open('file1.txt'), File.open('file2.txt') ] }
HTTParty.post(url, body: body)
Run Code Online (Sandbox Code Playgroud)
我从Web服务呼叫获得的响应如下:
#<HTTParty::Response:0x557d7b549f90 parsed_response={"error"=>true, "error_code"=>"invalid_attachment", "error_message"=>"Attachmen
t(s) not found or invalid."}, @response=#<Net::HTTPBadRequest 400 Bad Request readbody=true>, @headers={"server"=>["nginx"], "date"=>[
"Mon, 20 May 2019 07:41:50 GMT"], "content-type"=>["application/json"], "content-length"=>["102"], "connection"=>["close"], "vary"=>["
Authorization"], "set-cookie"=>["c18664e1c22ce71c0c91742fbeaaa863=uv425hihrbdatsql1udrlbs9as; path=/"], "expires"=>["Thu, 19 Nov 1981
08:52:00 GMT", "-1"], "cache-control"=>["no-store, no-cache, must-revalidate", "private, must-revalidate"], "pragma"=>["no-cache", "no
-cache"], "x-ratelimit-limit"=>["60"], "x-ratelimit-remaining"=>["59"], …Run Code Online (Sandbox Code Playgroud) Rails 5引入了新的表单辅助方法form_with.
它form_for是如何不同的,何时更适合使用?
这是我的凭证模型:
class Credential < ApplicationRecord
validate :password_or_certificate
enum credential_type: { windows: 1, linux: 2 }
def password_or_certificate
unless user_pass.blank? ^ cert_file_path.blank?
errors.add(:base, "Please provide a password or a certificate, not both.")
end
end
end
Run Code Online (Sandbox Code Playgroud)
我正在检查控制器中的证书并在控制器中设置错误,如下所示:
def create
attachment = params[:credential][:cert_file_path]
cert_file_path = Rails.root.join('private', 'certificates', attachment.original_filename) if attachment.present?
@credential = Credential.new(credential_params)
@credential.cert_file_path = cert_file_path
if @credential.valid? && cert_file_path.present?
cert_error_msg = 'Certificate is not valid'
fm = FileMagic.new(FileMagic::MAGIC_MIME)
file_path = attachment.path
if fm.file(file_path) =~ /^text\//
puts first_line = File.open(attachment.path) { |f| f.readline …Run Code Online (Sandbox Code Playgroud) 我将有两个Rails应用程序,一个是成熟的应用程序,另一个是简化的应用程序。这两个应用程序都有自己的数据库,它们将使用API相互通信。
我有两个这样的模型(在两个应用程序中):
class Scan < ApplicationRecord
has_many :background_processes, dependent: :destroy
end
class BackgroundProcess < ApplicationRecord
belongs_to :scan
end
Run Code Online (Sandbox Code Playgroud)
现在,当两个应用程序之间发生同步时,从属模型(在这种情况下background_processes)将具有不同的scan_id。
如果发生数据同步,我们应该如何处理关联?
我有以下三个模型:Product,Warehouse和Inventory
# app/models/product.rb
class Product < ApplicationRecord
has_many :inventories
has_many :warehouses, through: :inventories
end
# app/models/warehouse.rb
class Warehouse < ApplicationRecord
has_many :inventories
has_many :products, through: :inventories
end
# app/models/inventory.rb
class Inventory < ApplicationRecord
belongs_to :product
belongs_to :warehouse
end
Run Code Online (Sandbox Code Playgroud)
我有这个库存工厂:
FactoryBot.define do
factory :inventory do
product { nil }
warehouse { nil }
item_count { 1 }
low_item_threshold { 1 }
end
end
Run Code Online (Sandbox Code Playgroud)
我如何将这个工厂用于库存,或者我的其他工厂需要进行哪些更改,以便我可以拥有这样的规范?
RSpec.describe Inventory, type: :model do
it "has a valid factory" do
expect(FactoryBot.build(:inventory)).to …Run Code Online (Sandbox Code Playgroud) 我们可以使用列标题指定使用roogem 解析excel表的列号吗?我当前的代码现在是这样的:
oo = Openoffice.new("simple_spreadsheet.ods")
oo.default_sheet = oo.sheets.first
(2..oo.last_row).each do |line|
date = oo.cell(line,'A')
start_time = oo.cell(line,'B')
end_time = oo.cell(line,'C')
pause = oo.cell(line,'D')
...
end
Run Code Online (Sandbox Code Playgroud)
我想从列标题解析,而不是将列指定为'A' 'B' 'C' ..。我可以使用Roo吗?
我有两个带有enum字段的模型:
class TempAsset < ApplicationRecord
enum state: { running: 0, stopped: 1, terminated: 2 }
end
class AssetCredential < ApplicationRecord
enum map_status: { pending: 0, inprogress: 1, passed: 2, failed: 3 }
end
Run Code Online (Sandbox Code Playgroud)
当我从第一个表中选择列时,它会从枚举中给出正确的值:
TempAsset
.joins('INNER JOIN asset_credentials
ON temp_assets.instance_id = asset_credentials.instance_id')
.pluck(:state)
.uniq
# ["stopped", "running"]
Run Code Online (Sandbox Code Playgroud)
但是,当我从连接表中选择列时,它会给出数字:
TempAsset
.joins('INNER JOIN asset_credentials
ON temp_assets.instance_id = asset_credentials.instance_id')
.pluck(:map_status)
.uniq
# [0, 3, 2, 1]
Run Code Online (Sandbox Code Playgroud)
那么,我应该这样做:
AssetCredential.map_statuses.key(0) => "pending"
AssetCredential.map_statuses.key(1) => "inprogress"
Run Code Online (Sandbox Code Playgroud)
或者有没有更好的方法来做同样的事情?
我试图将局部变量从控制器传递到视图:
# pages_controller.rb
def my_method
render template: "pages/new_page", message: @message
end
# new_page.html.erb
<% if message %>
Do something
<% else %>
Do something else
<% end %>
Run Code Online (Sandbox Code Playgroud)
但这给了我未定义的局部变量或方法message错误,而在部分情况下这可以正常工作。
我知道这可以这样解决:
def my_method
render template: "pages/new_page", locals: { message: @message }
end
Run Code Online (Sandbox Code Playgroud)
我只是想知道,在没有当地人的情况下,这是如何工作的。
ruby-on-rails local-variables actionview partials actioncontroller
ruby ×4
actionview ×2
activerecord ×1
associations ×1
factory-bot ×1
httparty ×1
httpclient ×1
javascript ×1
partials ×1
rspec ×1
ruby-roo ×1
simple-form ×1
web-services ×1