form_for 没有 ActiveRecord,表单动作不更新 [英] form_for without ActiveRecord, form action not updating

查看:36
本文介绍了form_for 没有 ActiveRecord,表单动作不更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 API 而不是数据库,所以我不使用 ActiveRecord 而是使用 ActiveModel(我最喜欢这里:railscasts.com/episodes/219-active-model)

I'm using an API instead of a database, so I'm not using ActiveRecord but ActiveModel (I mostly did like here: railscasts.com/episodes/219-active-model)

事情是,当我尝试编辑一个项目(在我的例子中是停车)时,表单的操作仍然是创建而不是更新的操作.

Thing is, when I try to edit an item (in my case a parking), the action of the form still remains the action of the create and not update.

所以当我继续/parkings/2/edit 编辑停车时,表单仍然是:

so when I go on /parkings/2/edit to edit a parking, the form is still:

<form accept-charset="UTF-8" action="/parkings" class="form-horizontal" id="new_parking" method="post">

当它应该更像放置隐藏字段和停车场/2作为动作时:

when it should be more like that with the put hidden field and the parkings/2 as the action:

<form accept-charset="UTF-8" action="/parkings/2" class="form-horizontal" id="edit_parking" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="&#x2713;" /><input name="_method" type="hidden" value="put" />

任何人都知道方法和方法在哪里?form_for 的动作是根据路线设置的?我想要做的是尽可能接近我在数据库中使用 ActiveRecord.

Anybody knows where the method & action of the form_for is set according to the route? What I'm trying to do is be as close as if I was using ActiveRecord with a database.

这是一些代码:

_form.html.erb

<%= form_for(@parking, :html => { :class => "form-horizontal" }) do |f| %>
...
<% end %>

edit.html.erb &new.html.erb,简直了

<%= render 'form' %>

控制器

class ParkingsController < ApplicationController
  def index    
    @parkings = Parse.get("Parking")

    respond_to do |format|
      format.html
      format.json { render :json => @parking }
    end
  end

  def new
    @parking = Parking.new

    respond_to do |format|
      format.html
      format.json { render :json => @parking }
    end
  end

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

    respond_to do |format|
      format.html
      format.json { render :json => @parking }
    end
  end

  def create
    @parking = Parking.new(params[:parking])
    if (@parking.save)
       flash[:success] = "Parking was just added!"
       redirect_to :action => "new"
    else
      render :action => "new"
    end
  end

  def update
   # Testing
   parking = Parse.get("Parking", params[:id])
   parking.delete("updatedAt")
   parking["name"] = params[:parking][:name]
   parking.save

   redirect_to :action => "index"
  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

  @id = nil

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

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

    parking = Parking.new
    parking.name              = raw["name"]
    parking.address           = raw["address"]
    parking.city              = raw["city"]
    parking.longitude         = raw["location"]["longitude"]
    parking.latitude          = raw["location"]["latitude"]
    parking.contributor_name  = raw["contributorName"]
    parking.contributor_email = raw["contributorEmail"]

    return parking
  end

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

      data =
      {
        :longitude => longitude.to_f,
        :latitude  => latitude.to_f
      }

      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

请注意,创建工作正常,如果我使用 Web Inspector 或 Firebug 在表单 action="" 中添加我的停车 ID,并在我的 form_for 中添加 :method => "put",我的记录成功更新.

Please note that the create is working and if I add the id of my parking in the form action="" using the Web Inspector or Firebug, and add :method => "put" in my form_for, my record successfully update.

这里真正的问题是 form_for action &在我编辑停车位时不会更新的方法,就像我添加一个新的一样.

The real problem here is really the form_for action & method who doesn't get updated when I'm editing a parking and remains like if I was adding a new one.

我还在学习Rails,如果有些信息不清楚,请见谅!

I'm still learning Rails, so sorry if some infos aren't clear!

谢谢!

--- 解决方案 ---

坚持?不应该只返回 false,我的模型需要定义一个返回对象 id 的方法(以便他们可以更新 action=""),所以这是我更新的模型:

persisted? shouldn't only return false, and my model needed to define a method that returns the id of the object (so they can update the action="") so here's is my updated model:

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

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

  @id = nil

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

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

    parking = Parking.new
    parking.objectId          = id
    parking.name              = raw["name"]
    parking.address           = raw["address"]
    parking.city              = raw["city"]
    parking.longitude         = raw["location"]["longitude"]
    parking.latitude          = raw["location"]["latitude"]
    parking.contributor_name  = raw["contributorName"]
    parking.contributor_email = raw["contributorEmail"]

    return parking
  end

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

      data =
      {
        :longitude => longitude.to_f,
        :latitude  => latitude.to_f
      }

      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 update_attributes(aParking)
    parking = Parse.get("Parking", @id.to_s)
    parking.delete("updatedAt")

    parking["name"] = aParking["name"]
    parking.save

    return true
  end

  def destroy
    parking = Parse.get("Parking", @id)
    #parking.parse_delete
  end

  def id
    return self.objectId
  end

  def persisted?
    !(self.id.nil?)
  end
end

推荐答案

我认为您的问题出在模型的 persisted? 方法中.由于它总是返回 false,Rails 总是认为它正在为新创建的记录构建一个表单,因此它使用 POST 并提交到集合 URL.

I think your problem is in your model's persisted? method. Since it always returns false, Rails always thinks it's building a form for a newly created record, so it uses POST and submits to the collection URL.

您需要在该方法中使用某种逻辑,以便现有记录返回 true,新记录返回 false.

You need some sort of logic in that method so that existing records return true and new records return false.

这篇关于form_for 没有 ActiveRecord,表单动作不更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆