0

最初,我有两个模型:“用户”和“线程”。用户有很多线程,线程有一个用户。

现在,我添加了一个名为“Publications”的 JOIN,并调整了原来的“Users”和“Thread”模型。但是,当我创建一个新线程时,JOIN 表(出版物)中没有添加任何记录,并且“线程”表中的“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 值在表中为空:

= 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
4

1 回答 1

0

在控制器中:

@user = User.find(params[:id])
@thread = @user.threads.create(params[:thread])
于 2013-06-30T19:40:31.487 回答