簡體   English   中英

Rails:在has_many:through關系中未創建JOIN

[英]Rails: JOIN not being created in has_many :through relationship

最初,我有兩個模型:“用戶”和“線程”。 用戶有多個線程,而線程有一個用戶。

現在,我添加了一個名為“ Publications”的JOIN,並調整了原始的“ Users”和“ Thread”模型。 但是,當我創建一個新線程時,沒有記錄添加到JOIN表(發布)中,並且“ Threads”表中的“ user_id”列為空–沒有錯誤。

------------更新------------

我已經取得了一些進展-現在可以成功創建發布,並使用thread_id保存該發布。 但是,user_id仍為空。 我在下面添加了控制器操作。

以下是我的用戶模型:

class User < ActiveRecord::Base

    devise :database_authenticatable, :registerable, :confirmable,
           :recoverable, :rememberable, :trackable, :validatable

    attr_accessible :email, :password, :password_confirmation, 
                    :remember_me, :username, :profile_image, 
                    :first_name, :last_name

    has_many :publications
    has_many :threads, :through => :publications

end

以下是我的出版物模型:

class Publication < ActiveRecord::Base
  attr_accessible :thread_id, :user_id
  belongs_to :thread
  belongs_to :user
end

下面是我的線程模型:

class Thread < ActiveRecord::Base
  attr_accessible :description, :name, :tag_list, :thumbnail_image, :status, :thread_type, :subtitle, :summary

  has_one :publication
  has_one :user, :through => :publication

end

下面是我用來創建新線程的表單–創建新線程時,沒有任何內容添加到發布中,並且該線程的user_id值在表中為null:

= form_for [@user, @thread] do |f|
  - if @thread.errors.any?
    #error_explanation
      %h2= "#{pluralize(@thread.errors.count, "error")} prohibited this thread from being saved:"
      %ul
        - @thread.errors.full_messages.each do |msg|
          %li= msg

  .field
    %span Title:
    = f.text_field :name

  .actions
    = f.submit 'Submit'    

以下是我的控制器操作:

def create
  @user = User.find(params[:user_id])
  @thread = @user.threads.new(params[:thread])
  @thread.build_publication
end

在控制器中:

@user = User.find(params[:id])
@thread = @user.threads.create(params[:thread])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM