Ruby on Rails的关系参考节约
问题描述:
我只是想知道什么是节约这类数据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,让轨道解析它
答
你可以写这样的事情:
@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))
更新:
或者你可以添加一个scope
您Comment
型号:
# 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
请澄清你们的关系正在有点混乱,有人拿到你的问题。 – 2014-12-02 07:58:17
嗨Bharat soni我认为这种关系不够复杂 – 2014-12-02 08:09:18