cmw
cmw

Reputation: 956

Rails: Null user_id with has_many :through

I have three models: "Users", "Publications" and "Threads". Users and threads are objects, and publications is a join (using has_many :through).

When a user creates a new thread, both the thread and its join (publication) are created successfully – this is great. The only problem is, the user_id is null in both.

For reference, I'm using devise.

Below is my users model:

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

Below is my publications model:

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

Below is my threads model:

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

Below is the form I'm using to create a new thread:

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

Below is my create action in the thread controller:

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

Below is the publications table:

class CreatePublications < ActiveRecord::Migration
  def change
    create_table :publications do |t|
      t.integer :user_id
      t.integer :thread_id

      t.timestamps
    end
  end
end

All objects are created successfully, I just can't seem to get the user_id to go through.

Upvotes: 0

Views: 399

Answers (1)

fabsays
fabsays

Reputation: 171

I believe there needs to be a slight change in the create action of your thread controller:

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

You'll notice the second line of that action now uses create instead of new. The create command will make a new thread and save it as well.

Upvotes: 1

Related Questions