2015-03-19 119 views
0

我對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 

回答

0

你可以這樣做:

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

0

你可能這得太多。鑑於你想要做的簡單的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

相關問題