【问题标题】:My has_many - belongs_to tables in ruby on rails don't seem to be related.我在 ruby​​ on rails 中的 has_many - belongs_to 表似乎不相关。
【发布时间】:2016-09-04 13:51:35
【问题描述】:

我在 ruby​​ on rails 上制作了具有 1:N 关系的“hospital_review”表和“hospital_review_cmets”表。 'hospital_review'表的迁移文件是这样的。

class CreateHospitalReviews < ActiveRecord::Migration
def change
     create_table :hospital_reviews do |t|
       t.string :written_time
       t.string :writter
       t.integer :user_id
       t.string :category
       t.string :hospital_name 
       t.text :content
      end
   end

和'hospital_review_cmets'的一个是这样的。

   def change
     create_table :hospital_review_comments do |t|
       t.integer :user_id
       t.integer :post_id
       t.string :writter
       t.string :written_time
       t.text :content

      t.timestamps null: false
    end
  end

'hospital_review'表的模型文件是这样的。

belongs_to :user
has_many :hospital_review_comments

'hospital_review_cmets'表是这样的。

belongs_to :user
belongs_to :hospital_review

我想展示每个医院的评论和上面写的 cmets,所以我在“show.html.erb”中编写了以下代码。

<% @post.hospital_review_comments.each do |comment| %>
<p><strong><%=comment.user.username%></strong> <%=comment.content%></p>

这是在控制器文件中显示动作。

def show
@post = HospitalReview.find(params[:id])
@hospital_comment_writer = User.where(id: session[:user_id])[0]
end

但消息出现错误

'SQLite3::SQLException: no such column:'. 

我在 hospital_review_cmets 表的模型文件中尝试了“foregin_key”,但没有成功。我无法得到错误发生的原因。请帮忙!

【问题讨论】:

    标签: ruby-on-rails ruby sqlite3-ruby


    【解决方案1】:

    您的 hospital_review_cmets 表中缺少 hospital_review_id

    【讨论】:

    • 我将 post_id 更改为 hospital_review_id,并且。现在它起作用了!非常感谢
    【解决方案2】:

    我认为您在 hospital_review_cmets 表中错误地添加了post_id,应该是hospital_review_id,这将适用于工作。

    否则,您可以在关联中添加foreign_key 选项,如下所示。

    has_many :hospital_review_cmets, foreign_key: 'post_id'

    【讨论】:

      猜你喜欢
      • 2017-09-26
      • 2011-04-21
      • 1970-01-01
      • 1970-01-01
      • 2015-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多