如何更新表中的记录与当前记录的ID

问题描述:

我对Ruby和Rails相当新,并没有内部化它很多。我面临的问题似乎应该很容易解决,但对我来说这并不简单。如果我的一些术语不准确,我很抱歉。如何更新表中的记录与当前记录的ID

版本:Rails 4.2.0 |红宝石2.1

我有机型主题邮政 & 简介。 帖子嵌套在主题,所以当我create一个帖子,我能够与subject_id更新帖子表所示:嵌套下

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

综述,并且属于一个帖子。当创建一个摘要我想更新的帖子summary_id。我无法将自己的头围绕在如何去做,也无法找出Stack Overflow或其他地方。

如果它是一个SQL命令,并且当前帖子的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 
+0

看起来不错,我会给它一个镜头。仍然与语法摔跤。 – 2015-03-19 02:53:11

你可能这得太多。鉴于你想要做的简单的SQL命令:

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

你只需要做这样的事情来完成。

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

对。是的,这就是我可以手动执行的方式,我无法在'create'方法中找到它的语法。谢谢。 – 2015-03-19 02:54:10