在Ruby on Rails项目上,我试图在将所有内容保存到数据库之前访问ActiveRecord上的关联对象.
class Purchase < ActiveRecord::Base
has_many :purchase_items, dependent: :destroy
has_many :items, through: :purchase_items
validate :item_validation
def item_ids=(ids)
ids.each do |item_id|
purchase_items.build(item_id: item_id)
end
end
private
def item_validation
items.each do |item|
## Lookup something with the item
if item.check_something
errors.add :base, "Error message"
end
end
end
end
Run Code Online (Sandbox Code Playgroud)
如果我像这样构建我的对象:
purchase = Purchase.new(item_ids: [1, 2, 3])并尝试保存它,item_validation方法没有填充项目集合,所以即使已设置项目设置,它也没有机会check_something在其中任何一个上调用方法.
是否可以在我的购买模型和关联模型持久化之前访问项目集合,以便我可以对它们运行验证?
如果我改变我的item_validation方法是:
def item_validation
purchase_items.each do |purchase_item|
item = purchase_item.item
## Lookup something with the item
if item.something …Run Code Online (Sandbox Code Playgroud) 我正在使用Ruby 1.8.7.我有以下哈希数组.我需要先按布尔值排序,但这些结果必须按原始顺序排序.我基本上需要将所有真正的哈希值移到数组的顶部,但保持原始顺序.
任何帮助,将不胜感激!
array = [{:id => 1, :accepts => false},
{:id => 2, :accepts => false},
{:id => 3, :accepts => true},
{:id => 4, :accepts => false},
{:id => 5, :accepts => true}]
sorted = array.sort do |x, y|
if x[:accepts] == y[:accepts]
0
elsif x[:accepts] == true
-1
elsif x[:accepts] == false
1
end
end
Run Code Online (Sandbox Code Playgroud)
我得到的这种产量:
5 - 真
3 - 真
2 - 假
4 - 假
1 - 假
我需要它来产生:
3 - 真
5 - …
我有一个方法,其中包含一个开始/救援块.如何使用RSpec2测试救援块?
class Capturer
def capture
begin
status = ExternalService.call
return true if status == "200"
return false
rescue Exception => e
Logger.log_exception(e)
return false
end
end
end
describe "#capture" do
context "an exception is thrown" do
it "should log the exception and return false" do
c = Capturer.new
success = c.capture
## Assert that Logger receives log_exception
## Assert that success == false
end
end
end
Run Code Online (Sandbox Code Playgroud) 有没有人知道是否有办法通过跟踪获得与Commission Junction广告商的直接链接?我们不想依赖于Feed中发送的链接,因为其中很多都是垃圾.
我想要的是一个链接,只是去广告主的主页,仍然允许我们收到佣金.类似的东西:http://www.newegg.com? pid = 123123&aid = 321123
如果它必须通过CJ的跟踪URL也很好,但我只想让用户在主页上.
谢谢