【问题标题】:How to associate two foreign key to a post on create如何将两个外键关联到创建帖子
【发布时间】:2012-04-28 12:12:04
【问题描述】:

我有以下 3 个模型,并希望将两个外键关联到创建帖子(user_id(来自用户模型)和 review_id(来自评论模型)到目标模型。我设法使用“current_user”关联 user_id使用下面链接中给出的解决方案来创建目标,但不确定如何为 review_id 完成这项工作。

谢谢。

Devise how to associate current user to post?

我的模型:

class User < ActiveRecord::Base       
  has_many :reviews
  has_many :periods, :through => :reviews
  has_many :goals
end

class Review < ActiveRecord::Base       
  belongs_to :user
  belongs_to :period
  has_many :goals
end

class Goal < ActiveRecord::Base       
  belongs_to :user
  belongs_to :review
end

我的目标控制器.rb

def create
  @goal = current_user.goals.build(params[:goal])

  respond_to do |format|
    if @goal.save
      format.html { redirect_to @goal, notice: 'Goal was successfully created.' }
      format.json { render json: @goal, status: :created, location: @goal }
    else
      format.html { render action: "new" }
      format.json { render json: @goal.errors, status: :unprocessable_entity }
    end
  end
end

干杯, 阿兹伦

【问题讨论】:

  • 你已经发布了两次User 模型。
  • 再次检查。还有 2 个class User 语句。虽然你已经修复了他们的内容。

标签: ruby-on-rails


【解决方案1】:

虽然我不明白目标是什么。我通常使用的一种通用方法是将关系建模为您熟悉的事物,或者您可以轻松找到好的示例。例如,将您的用例视为用户问答模型。与您的用例相同,用户有很多问题和很多答案。 question有很多答案,属于用户,答案属于用户和问题。

所以事情变得容易了,对吧?让我们看看stackoverflow是如何实现的。您可以查看评论框的 html 代码,表单操作类似于 (/questions/10186415/answer/submit)。这里 10186415 是问题 id,它是传递给服务器端的,所以在创建答案时,可以使用此问题 id 并关联。

回到您的案例,目标表单应该知道它的用途。评论 ID 可以是隐藏字段,也可以是提交网址的一部分。

【讨论】:

  • 我已将 '@review = Review.where("user_id = current_user")' 添加到控制器 'create' 和我的目标表单中 ' @review %>'。它保存成功,但没有 review_id。有什么想法吗?
猜你喜欢
  • 2020-06-21
  • 2012-08-08
  • 1970-01-01
  • 1970-01-01
  • 2011-01-04
  • 1970-01-01
  • 2020-09-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多