2014-12-02 64 views
0

我只是想知道什麼是節約這類數據Ruby on Rails的關係參考節約

這裏的最佳實踐年代車型

class User < ActiveRecord::Base 
    has_many :posts, dependent: :destroy 
    has_many :comments, dependent: :destroy 
end 

class Comment < ActiveRecord::Base 
    belongs_to :post 
    belongs_to :user 
end 

class Post < ActiveRecord::Base 
    belongs_to :user 
    has_many :reviews 
end 

目前我保留他們在這之間的關係代碼類型

def create 
    @post = Post.find(params[:post_id]) 
    @comment = current_user.reviews.build(comment_param) 
    @comment.post_id = params[:post_id] 
    if @comment.save 
     flash[:success] = 'Successfully created a comment' 
     @post 
    else 
     flash[:error] = 'Error' 
     @post 
    end 
end 

下面是窗體的開始標記。

form_for([@post,@post.comment.build]) do |f| 
    %p 
     = f.label :title, class: 'control-label' 
     = f.text_field :title, class: 'form-control' 
    %p 
     = f.label :message, class: 'control-label' 
     = f.text_area :message, class: 'form-control' 

我如何可以通過快捷鍵,以便我不會手動分配POST_ID,讓軌道解析它

+0

請澄清你們的關係正在有點混亂,有人拿到你的問題。 – 2014-12-02 07:58:17

+0

嗨Bharat soni我認爲這種關係不夠複雜 – 2014-12-02 08:09:18

回答

0

你可以寫這樣的事情:

@comment = current_user.comments.build(comment_param.merge(:post_id => params[:post_id])) 

@post = Post.find(params[:post_id]) 
@comment = @post.comments.build(comment_param.merge(:user => current_user)) 

更新:

或者你可以添加一個scopeComment型號:

# in comment.rb 
scope :by_user, ->(user) { where(:user_id => user.id) } 

# and then in the controller 
@post = Post.find(params[:post_id]) 
@comment = @post.comments.by_user(current_user).build(comment_param) 
+0

hi @spickermann被認爲是最佳做法嗎?謝謝 – 2014-12-02 08:10:19

+0

@PrettyOdd:我更新了我的答案,並建議採用第三種方案。 – spickermann 2014-12-02 08:34:11