如何使用当前记录的 ID 更新 table 中的记录

How do I update a record in a table with current record's id

我对 Ruby 和 Rails 都很陌生,还没有深入了解其中的很多内容。我面临的问题看起来应该很容易解决,但对我来说并不简单。如果我的某些术语不准确,我深表歉意。

版本:Rails4.2.0 | Ruby2.1

我有模型主题Post概要。 Posts 嵌套在主题下,所以当我 create a Post 我能够更新 posts table 和 subject_id 像这样:

def create
    @subject = Subject.find(params[:subject_id])
  @post = current_user.posts.build(params.require(:post).permit(:title, :body))
  @post.subject = @subject
...

摘要嵌套在 Post 下并属于一个 Post。创建摘要时,我想 posts table 更新为 summary_id。我只是不知道该怎么做,也无法在 Stack Overflow 或其他地方找到方法。

如果是SQL命令,当前post的id为23,当前概要的id为9,则为像 UPDATE posts SET posts.synopsis_id = 9 WHERE posts.id = 23.

相关的控制器、模型和架构信息如下。如果我需要提供更多信息,请告诉我。

控制器:

synopses_controller.rb

def create
    @subject = Subject.find(params[:subject_id]) #find the Subject id
    @post = Post.find(params[:post_id]) #find the post id
  @synopsis = Synopsis.new(params.require(:synopsis).permit(:name, :description))
  #UPDATE THE POST WITH SYNOPSIS_ID!
  if @synopsis.save
    flash[:notice] = "Synopsis was saved."
    redirect_to [@subject, @post, @synopsis] #go to the Synopsis page
  else
    flash[:error] = "There was an error saving the Synopsis. Please try again."
    render :show
  end
end

型号:

synopsis.rb

class Synopsis < ActiveRecord::Base
  belongs_to :post
end

post.rb

class Post < ActiveRecord::Base
 has_one :synopsis
 has_many :comments
 belongs_to :user
    belongs_to :subject
end

架构:

schema.rb

create_table "posts", force: :cascade do |t|
 t.string   "title"
 t.text     "body"
 t.datetime "created_at", null: false
 t.datetime "updated_at", null: false
 t.integer  "user_id"
 t.integer  "subject_id"
 t.integer  "synopsis_id"
end

create_table "synopses", force: :cascade do |t|
 t.string   "name"
 t.text     "description"
 t.datetime "created_at",  null: false
 t.datetime "updated_at",  null: false
end

你可以这样做:

def create
  # ....
  if @synopsis.save
    @post.update(:synopsis_id, @synopsis.id)
    flash[:notice] = "Synopsis was saved."
    redirect_to [@subject, @post, @synopsis] #go to the Synopsis page
  else
  #....
end

你可能想多了。鉴于您想要执行的简单 sql 命令:

UPDATE posts SET posts.synopsis_id = 9 WHERE posts.id = 23

你只需要做这样的事情就可以做到这一点。

Post.find(23).update(:synopsis_id => 9)