gpt4 book ai didi

ruby-on-rails - Self.find 方法 Active Model in Rails 不起作用

转载 作者:数据小太阳 更新时间:2023-10-29 07:57:10 24 4
gpt4 key购买 nike

我目前使用的是 API 而不是数据库,我想尽可能接近 ActiveRecord,所以我决定继续并完全像这里的 railscast:http://railscasts.com/episodes/219-active-model

到目前为止,我的保存方法运行良好,因此我可以将数据保存到 API。我的问题出在编辑上,我的查找方法似乎是问题所在...这是一些代码!

在我的 Controller 中编辑方法

  def edit
@parking = Parking.find(params[:id])
end

整个模型

class Parking
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming

attr_accessor :name, :address, :city, :longitude, :latitude, :contributor_name, :contributor_email

validates_presence_of :name, :address, :city, :longitude, :latitude

def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
end

def self.find(id)
parking = Parse.get("Parking", id.to_s) // API Call

name = parking["name"]
address = parking["address"]
city = parking["city"]
longitude = parking["location"]["longitude"]
latitude = parking["location"]["latitude"]
contributor_name = parking["contributorName"]
contributor_email = parking["contributorEmail"]

return self
end

def save
if (!valid?)
return false
else
parking = Parse::Object.new("Parking")

data =
{
:longitude => 40.0,
:latitude => -30.0
}

point = Parse::GeoPoint.new(data)

parking["location"] = point
parking["name"] = name
parking["address"] = address
parking["city"] = city
parking["contributorName"] = contributor_name
parking["contributorEmail"] = contributor_email

if (parking.save)
return true
end
end
end

def persisted?
false
end
end

这是我目前得到的错误:

undefined method `to_key' for Parking:Class

提取的源代码(大约第 1 行):

1: <%= form_for(@parking, :html => { :class => "form-horizontal"}) do |f| %>
2: <% if @parking.errors.any? %>
3: <div class="alert alert-error fade in">
4: <a class="close" data-dismiss="alert">×</a>**

如果有人提出建议,我真的对任何想法持开放态度,我从 rails 开始:)

谢谢!

编辑:

当我在我的 Controller 编辑方法中做类似的事情时:

  def edit
@parking = Parking.new
@parking.name = "foo"
@parking.address = "foo"
@parking.city = "foo"
@parking.longitude = "foo"
@parking.latitude = "foo"
end

我的 View 在每个字段中加载 foo 没问题,所以问题是我一定是 find 方法做错了:)

最佳答案

一个问题是您的find 方法是一个类方法(由于是“self.find”),这意味着它不对类,因此不知道实例变量/方法,例如 nameaddress

实现 find 的更好方法是实例化 Parking 的新实例,并填充它的变量,然后返回它,例如

def self.find(id)
raw = Parse.get("Parking", id.to_s)

parking = Parking.new
parking.name = raw["name"]
# etc for the others

parking # Return the newly-created instance
end

这并不能解释您当前看到的“未定义方法”,您可能需要发布更多详细信息才能获得答案,特别是从异常中进行完整回溯以查看实际引发了哪些代码它。根据您提供的信息,我猜是 Parse.get 方法中的某些内容导致了它。

关于ruby-on-rails - Self.find 方法 Active Model in Rails 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9561844/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com