我的模特有:
class Link < ActiveRecord::Base
belongs_to :group
validates_presence_of :url_address
validates_presence_of :group_id
before_save :verify_url
acts_as_list
def valid_get?
HTTParty.get(url_address).code.between?(100,399) ? true : false
rescue SocketError, URI::InvalidURIError
false
end
def verify_url
if valid_get?
verified_date = Time.now
end
end
end
当我通过表单创建记录时,verified_date被正确设置为今天的日期。
为什么不更新字段以更新记录?
控制器:
class LinksController < ApplicationController
before_filter :authorize, :except => [:index, :show, :advanced_search]
...
def verify_link # Used by js. works fine to update the field.
@link = Link.find(params[:id])
if @link.valid_get?
if @link.update_attribute(:verified_date, Time.now)
render nothing: true, status: 200
else
render nothing: true, status: 422
end
else
render nothing: true, status: 422
end
end
def create # Used via the HTML form. method should update verified_date but doesn't
@link = Link.new(params[:link])
@link.content_date = Time.new().strftime("%m/%d/%Y") if @link.content_date.nil?
if @link.valid_get?
@link.verified_date = Time.new()
http_check_msg = 'and the url was verified as valid'
else
http_check_msg = 'however it was *not* possible to visit the url as given currently'
end
respond_to do |format|
if @link.save
flash[:notice] = 'Link was successfully created, ' + http_check_msg
format.html { redirect_to(@link) }
else
flash[:notice] = 'Error, The link was not created.'
@groups = Group.all.collect { |g| [g.group_name, g.id] }
format.html { render :action => "new"}
end
end
end
我有javascript通过上面的控制器verify_link方法更新该字段但是常规表单和附带的更新方法似乎没有更新更新方法中的属性 -
def update
@link = Link.find(params[:id])
respond_to do |format|
if @link.update_attributes(params[:link])
@link.verify_url
@link.save
flash[:notice] = 'Link was successfully updated.'
format.html { redirect_to(@link.group) }
else
@groups = Group.all.collect { |g| [g.group_name, g.id] }
format.html { render :action => "edit" }
end
end
end
答案 0 :(得分:2)
将您的方法更改为:
def verify_url
if valid_get?
self.verified_date = Time.now
end
end
请注意self.
。如果没有self
,您将创建一个新的局部变量,而不是更改模型属性。