隐式展开Bool类型似乎不起作用:
var aBoolean: Bool! // nil
aBoolean = false // false
aBoolean // false
aBoolean == true // false
aBoolean == false // true
if aBoolean {
"Hum..." // "Hum..."
} else {
"Normal"
}
if aBoolean! {
"Hum..."
} else {
"Normal" // "Normal"
}
Run Code Online (Sandbox Code Playgroud)
如果我已经宣布了aBoolean
这样的话var aBoolean: Bool?
,这将是预期的行为,但在这里,我不明白.
这是正确的行为吗?我没有找到任何关于它的文档.
谢谢!
举一个每个人都熟悉的例子,想想StackOverflow.用户has_many :questions
,has_many :answers
和她的问题和答案,可以评论.(评论是多态的).
我希望通过对该用户的问题或答案的评论来获得针对特定用户的所有回复:
class User < ActiveRecord::Base
has_many :questions
has_many :answers
has_many :comments
has_many :responses, through: [:questions, :answers], source: :comments
end
class Question < ActiveRecord::Base
belongs_to :user
has_many :answers
has_many :comments, as: :commentable
end
class Answer < ActiveRecord::Base
belongs_to :user
belongs_to :question
has_many :comments, as: :commentable
end
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
end
Run Code Online (Sandbox Code Playgroud)
当然,has_many :responses, through: [:questions, :answers], source: :comments
不起作用.
是否有Rails方法可以做到这一点?
谢谢.
如何从函数返回一个可变数组?
这是一段简短的代码片段,使其更加清晰:
var tasks = ["Mow the lawn", "Call Mom"]
var completedTasks = ["Bake a cake"]
func arrayAtIndex(index: Int) -> String[] {
if index == 0 {
return tasks
} else {
return completedTasks
}
}
arrayAtIndex(0).removeAtIndex(0)
// Immutable value of type 'String[]' only has mutating members named 'removeAtIndex'
Run Code Online (Sandbox Code Playgroud)
以下片段有效,但我必须返回一个Array
,而不是一个NSMutableArray
var tasks: NSMutableArray = ["Mow the lawn", "Call Mom"]
var completedTasks: NSMutableArray = ["Bake a cake"]
func arrayAtIndex(index: Int) -> NSMutableArray {
if index == 0 { …
Run Code Online (Sandbox Code Playgroud) Rails 3.1,Ruby 1.9.3
所以我有两个模型,都有两组坐标.
第一种模式,Load
具有from_lat/lng
,以及to_lat/lng
.
第二个型号,卡车,current_lat/lng
以及destination_lat/lng
.
我要做的是找到所有结果,current_lat/lng
或者destination_lat/lng
来自Load模型的to_lat/lng附近的Truck模型.
我的车道模型是这样的:
class Load < ActiveRecord::Base
has_many :trucks
geocoded_by :custom_geocode
after_validation :custom_geocode
def custom_geocode
var = Geocoder.coordinates([from_city,from_state].compact.join(','))
var2 = Geocoder.coordinates([to_city,to_state].compact.join(','))
self.from_lat = var.first
self.from_lng = var.last
self.to_lat = var2.first
self.to_lng = var2.last
end
end
Run Code Online (Sandbox Code Playgroud)
在我看来,我有:
<% for truck in @trucks %>
<li><%= truck.destination_lat %></li>
<% end %>
Run Code Online (Sandbox Code Playgroud)
目前我在load_controller中使用它:
def show
@load = Load.find(params[:id])
@trucks = Truck.near([@load.from_lat, @load.from_lng], 100, :order => …
Run Code Online (Sandbox Code Playgroud)