繁体   English   中英

Rails 更新操作未更新

[英]Rails update action not updating

尝试更新帖子的匿名性:

在视图中

<%= form_for (post), remote: true do |f| %>
                            <%= f.check_box :anonymous %>
                            <span>Anonymous</span>
                            <%= f.submit 'Save' %>
                        <% end %>

控制器

def update
@post = Post.find(params[:id])
if @post.update_attributes(permit_post)
  puts 'aaaaaaaaaaaaaaa'
  puts @post.anonymous === true
  puts 'aaaaaaaaaaaaaaa'
  respond_to do |format|
   format.html
   format.js
  end
end
end
private 
def permit_post
params.require(:post).permit(:image, :title, :long, :anonymous, :facenumber);
end

在控制台中

    Started PATCH "/posts/9" for 94.187.88.109 at 2016-09-16 20:58:09 +0000
Processing by PostsController#update as JS
  Parameters: {"utf8"=>"✓", "post"=>{"anonymous"=>"1"}, "commit"=>"Save", "id"=>"9"}
  User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 2]]
  Post Load (0.2ms)  SELECT  "posts".* FROM "posts" WHERE "posts"."id" = ?  ORDER BY created_at DESC LIMIT 1  [["id", 9]]
   (0.2ms)  begin transaction
   (0.1ms)  rollback transaction
   (0.1ms)  begin transaction
   (0.1ms)  rollback transaction
  Rendered posts/update.js.erb (0.1ms)
Completed 200 OK in 150ms (Views: 22.4ms | ActiveRecord: 0.9ms)

似乎没有错误,但属性没有更新。 感谢您的帮助更新模型

class Post < ActiveRecord::Base
include PublicActivity::Common
cattr_accessor :current_user
cattr_accessor :user_id
acts_as_votable
has_attached_file :image, styles: { medium: "550", large: "600", thumb: "100x100>" }, default_url: "/missing.png"
validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
belongs_to :user
belongs_to :category
validates :user_id, presence: true
validates :image, presence: true
has_many :comments

结尾

在我看来,验证没有通过。 正如您在控制台中看到的那样,没有您放置、打印的任何 puts 评估。 这意味着update_attributes返回false

为什么不使用byebug放置断点并评估@post.errors.messages.inspect ,以检查它为什么没有更新? 如果您不想在开发 gem 中包含 byebug,则另一个选项是Rails.logger.info(@post.errors.messages.inspect) 当然,这需要放在@post.update_attributesif结束的地方)

您在01中获得布尔值,但ruby理解truefalse 因此,您需要在保存之前将1转换为true ,将0转换为 false。 你可以像这样在Post模型中做到这一点

before_validation :convert_boolean

def convert_boolean
  self.anonymous = (anonymous != nil and anonymous != '0')      
end

为避免这种情况,您也可以在 params 中传递true / false而不是0 / 1

尝试这个

<%= f.check_box :anonymous, {}, true, false %>

希望有帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM