【发布时间】:2016-06-12 20:57:32
【问题描述】:
目前我有一个 Subscriber 模型,该模型具有多个 comments 和一个属于 Subscriber 的 comment 模型。我对 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