【问题标题】:Active Record Associations - Rails活动记录关联 - Rails
【发布时间】:2016-06-12 20:57:32
【问题描述】:

目前我有一个 Subscriber 模型,该模型具有多个 comments 和一个属于 Subscribercomment 模型。我对 Rails 很陌生,我想知道如何连接这两个模型?因此,当我创建评论时,它具有发表评论的特定订阅者的 ID。现在我有一个视图,用户可以在其中输入他们最喜欢的饮料,我希望该评论有一个所有者。为了清楚起见,我将显示我的代码。谢谢!

评论控制器:

 class CommentsController < ApplicationController
 def new
  @comment = Comment.new
 end

 def create
  @comment = Comment.create(comments_params)
   if @comment.save
    flash[:notice] = "Subscriber Has Been Successfully Created"
    redirect_to new_subscriber_path(:comments)
   else
    render "new"
   end
  end

  private

  def comments_params
   params.require(:comment).permit(:fav_drink)
  end
end

订阅者控制器:

  class SubscribersController < ApplicationController
  def index
   @subscriber = Subscriber.all
  end

  def new
   @subscriber = Subscriber.new
  end

  def create
    @subscriber = Subscriber.create(subscriber_params)
    if @subscriber.save
     flash[:notice] = "Subscriber Has Been Successfully Created"
     redirect_to new_subscriber_path(:subscriber)
   else
    render "new"
   end
  end

评论模型:

 class Comment < ActiveRecord::Base
  belongs_to :subscriber 
 end

订阅者模型:

 class Subscriber < ActiveRecord::Base
   has_many :comments
 end

Comment 模型有一个subscriber_id,所以现在可以工作了在那个订阅者上。

【问题讨论】:

  • 您的创建评论操作有一些来自订阅者的工件,但除此之外,您的控制器代码和关联似乎还不错。您的迁移/模式和视图是什么样的?目前发送到 cmets 的 create 操作的参数是什么?

标签: ruby-on-rails ruby activerecord


【解决方案1】:

基本上这一行就是您要更新的行:@comment = Comment.create(comments_params)

如果您想将新记录与订阅相关联,您可以在传递给Comment.create 的属性哈希中包含一个subscriber_id 键。

虽然comments_param 是一个方法,但它会返回用于创建新记录的属性散列。在这种情况下,它可能是{ fav_drink: "Tea" },它需要有一个额外的 key-val 集。我不确定您打算如何获得subscriber_id,但您可能需要一个“当前用户”系统。

这是一个单独的讨论(如何在 Rails 中实现身份验证以获得“当前用户”的概念)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-10
    • 1970-01-01
    相关资源
    最近更新 更多